我在PyCharm上使用python 3.8。 我想创建一个GUI,我可以在其中选择创建目录或文件并为其命名。 这只是函数
def ask_add():
global aroot
aroot = Tk()
aroot.asking = True
name_var = StringVar()
aroot.geometry('500x400')
aroot.title('OOS')
aroot.config(bg='black')
# name label
name_label = Label(aroot, text='Name:', bg='black', fg='#00ff00', font=16)
name_label.grid(row=0, column=0, padx=20, pady=10)
# name entry
name_entry = Entry(aroot, bg='black', fg='#00ff00', insertbackground='#00ff00', textvariable=name_var, width=40)
name_entry.grid(row=0, column=1)
# type label
type_label = Label(aroot, text='Type:', fg='#00ff00', bg='black', font=16)
type_label.grid(row=1, column=0)
# type radio buttons
type_var = StringVar()
file_option = Radiobutton(aroot, bg='black', fg='#00ff00', text='File', font=16, variable=type_var, value='File', activebackground='#00ff00', activeforeground='black')
file_option.grid(row=1, column=1)
dir_option = Radiobutton(aroot, bg='black', fg='#00ff00', text='Dir', font=16, variable=type_var, value='Dir', activebackground='#00ff00', activeforeground='black')
dir_option.grid(row=2, column=1)
# create dir / file
create_button = Button(aroot, text='Create', bg='black', fg='#00ff00', font=18, activebackground='#00ff00', activeforeground='black', command=lambda: add(name_var.get(), type_var.get()))
create_button.grid(row=3, column=1)
while aroot.asking:
aroot.update()
这是add((函数
def add(n, t): # name, type
global aroot
aroot.asking = False
aroot.destroy()
print(n, t)
if t == 'File':
p = subprocess.Popen(f'echo.>{n}', shell=True, stderr=subprocess.PIPE)
err = str(p.stderr.read().decode())
if err != '':
tkinter.messagebox.showerror(title='Error', message=err)
else: # t == Dir
p = subprocess.Popen(f'md {n}', shell=True, stderr=subprocess.PIPE)
err = str(p.stderr.read().decode())
if err != '':
tkinter.messagebox.showerror(title='Error', message=err)
update() # updates a window that displays directories
我希望脚本将name_var和type_var传递给函数add((,但是当我输入条目或单击单选按钮时,这些变量不会更新(它们的值保持 ''(,因此函数add((无法创建任何文件或目录。 我还尝试在 while 循环中打印变量
while aroot.asking:
print(name_var.get(), type_var.get())
aroot.update()
但它们的价值仍然是"。有人可以告诉我我做错了什么吗?谢谢
解决了我的问题,只需在使用command=lambda: type_var.set(*my value*)
单击单选按钮时更改type_var的值即可。
file_option = Radiobutton(aroot, bg='black', fg='#00ff00', text='File', font=16, variable=type_var, value='File', activebackground='#00ff00', activeforeground='black', command=lambda: type_var.set('File'))
file_option.grid(row=1, column=1)
dir_option = Radiobutton(aroot, bg='black', fg='#00ff00', text='Dir', font=16, variable=type_var, value='Dir', activebackground='#00ff00', activeforeground='black', command=lambda: type_var.set('Dir'))
dir_option.grid(row=2, column=1)