我是Python的Tkinter的新手,我想创建一个在其上运行的程序。但是,我的代码不能正常工作。你知道吗
from tkinter import *
def conv1(self):
gbp0 = 174000000
galleons0 = 34000872
sickles0 = 14
knuts0 = 7
galleons1 = float(galleons0 + sickles0 / 17 + knuts0 / 29 / 17)
fracture = float(gbp0 / galleons1)
convert1 = Toplevel(root)
convert1.title("Pounds Sterling (GBP) to Galleons, Sickles and Knuts Converter")
label1_1 = Label(convert1, text="Type the amount of money in GBP that you would like to convert to Galleons, Sickles and Knuts and press Enter.")
label1_2 = Label(convert1, text="1 Galleon = 5.12 GBP")
label1_3 = Label(convert1, text='GBP:')
label1_1.pack()
label1_2.pack()
label1_3.pack()
usergbpvar = DoubleVar()
usergbp = Entry(convert1, textvariable=usergbpvar)
usergbp.pack()
a = float(usergbpvar.get() / fracture)
galleons = int(a // 1)
a = (a % 1) * 17
sickles = int(a // 1)
a = (a % 1) * 29
if (a % 1) == 0.5:
knuts = int(round(a, 0))
knuts += 1
else:
knuts = int(round(a, 0))
galleons, sickles, knuts = str(galleons), str(sickles), str(knuts)
label1_4 = Label(convert1, text=galleons)
label1_5 = Label(convert1, text=sickles)
label1_6 = Label(convert1, text=knuts)
label1_4.pack()
label1_5.pack()
label1_6.pack()
convert1.mainloop()
root = Tk()
btn1 = Button(root, text='GBP to Galleons, Sickles and Knuts', bg='#555', fg='#ccc', font='16')
btn1.pack()
btn1.bind('<Button-1>', conv1)
root.mainloop()
它应该从输入的数字中计算出三个数字,并在屏幕上显示出来。然而,当我运行程序,按下按钮后,我看到所有的数字已经在那里,他们是0。我输入号码后,什么也没变。你知道吗
你能告诉我代码中的问题在哪里吗?你知道吗
问题/问题1:
当你打电话的时候
label1_4=Label(convert1, text=galleons) label1_4.pack()
这告诉tkinter立即用给定的值显示标签,例如galleons代表label1\u 4,即0(其他标签相同)。这不是问题,因为输入框的值应该是0。你知道吗问题2:
实际上,您并没有告诉程序更新标签的值。正如TornaxO7所说,您需要绑定enter(return)键来调用函数
usergbp.bind("<Return>", calculation_function_here)
我已经编辑了您的代码以提供面向对象的方法。我建议您在开发过程中探索这种方法,可能需要多个窗口。Best way to structure a tkinter application?
问题/评论中的问题3: 我相信错误:
tkinter.TclError: grab failed: window not viewable
取决于您的操作系统。我无法在Mac OS上重现此错误,但添加self.master.wait_visibility()
(添加到我的代码中)可能会解决此问题: python tkinter treeview not allowing modal window with direct binding like on_rightclick我猜你忘了绑定
Return
-键。您应该在方法中添加
convert1.bind("<Return>", *your function*)
。“你的函数”是改变数字的函数。你知道吗
相关问题 更多 >
编程相关推荐