【发布时间】:2021-02-23 17:37:49
【问题描述】:
我正在从事一项涉及使用 openpyxl、tkinter 和 pandas 的任务。我需要根据一个输入(avg_trips)在 excel 中进行一些计算
这是当前代码。上传文件后,代码只要求在终端中输入。但我希望它在 tkinter 窗口中要求输入
def open_file():
file = askopenfile(mode ='a+', filetypes =[('Excel Files', '*.xlsx *.xlsm *.sxc *.ods *.csv *.tsv')])
wb = openpyxl.load_workbook(filename = file.name)
wb.create_sheet("Results")
avg_trips = float(input("Enter Shipping Frequency: "))
这是我尝试过的 tkinter 代码:
root = tk.Tk()
root.title("Optimization")
root.geometry('500x450')
frq = Label(root,text="Enter Shipping Frequency: ")
frq.pack()
frq.place(x =105,y=180)
def printtext():
global e
avg_trips = int(e.get())
e = Entry(root)
e.pack()
e.place(x=260,y=180)
button = Button(root,text='okay',command=printtext)
button.pack(side='bottom')
button.place(x=230,y=220)
lbl=Label(root, text="Optimization", fg='blue', width = 450,bg = 'light blue', font=("Helvetica", 16))
lbl.pack(side=TOP, fill=X)
btn = Button(root, text ='Upload File', command = open_file)
btn.place(x=210, y=150)
foot=Label(root, text="2021 Optimization",fg='blue',width = 450,bg = 'light blue',font=("Helvetica", 8))
foot.pack(side=BOTTOM, fill=X)
# avg_trips = Entry(root)
# # avg_trips = x.get()
btn = Button(root, text ='Run', command = excel)
btn.place(x=230, y=250)
root.mainloop()
我给出了相同的变量名 (avg_trips),但出现此错误:
NameError:名称“avg_trips”未定义
如何在 tkinter 文件中询问输入并且按钮触发其余过程?
【问题讨论】:
-
您在
root.title(Optimization")中缺少" -
avg_trips是一个局部变量,所以它只在printtext内部可见。 -
在
printtext定义的开头添加global avg_trips。 -
还有你为什么注释掉
# avg_trips = Entry(root)。 -
@CoolCloud,我在顶部创建了另一个条目