我是 TKinter 的新手,一直在尝试将我的普通 Python 代码转换为 GUI(TKinter 代码)!我一直在研究这段代码,到目前为止,我已经完成了基本布局,但是我在编码按钮和使用条目时遇到了问题。您很可能会在我的代码中发现很多错误,因此请注意! :D
我在窗口顶部有一个条目,我希望用户在条目中输入一个数字,然后我想在某些代码中使用条目中输入的文本( btn1()
)。我还希望用户按下一个按钮,然后该按钮运行一些代码,这些代码在按钮下方显示代码结果的标签( btn1()
函数中的标签)。
首先,我希望用户在条目中输入一个数字。然后,我希望用户单击条目下方的按钮。最后,我希望按钮后面的代码的结果显示在按钮下方(在标签中!)。
这是我的代码:
from tkinter import *
class window_design:
def __init__(self):
root=Tk()
root.title("Bag Weight")
root.geometry("500x700")
root.wm_iconbitmap('favicon.ico')
image=PhotoImage(file="Weight Program.png")
imagelabel=Label(root,image=image)
imagelabel.pack()
weightentrylabel=Label(root,text="Enter Weight!")
weightentrylabel.pack()
self.string=StringVar()
weightentry=Entry(root,textvariable=self.string)
weightentry.pack()
menutext=Label(root,text="What coin are you using?")
menutext.pack(side=LEFT)
values=['1p','2p','5p','10p','20p','50p','£1','£2','Exit']
def btn1(self,btn1code):
p1=3.56
p1should=356
if (self.string.get()) > p1should:
weightdif=(self.string.get())-p1should
coins=weightdif/p1
labeldif=Label(text=weightdif)
labelcoins=Label(text=coins)
elif (self.string.get()) < p1should:
weightdif=p1should-(self.string.get())
coins=weightdif/p1
labeldif=Label(text=weightdif)
labelcoins=Label(text=coins)
button1=Button(root,text="1p",command=btn1)
button1.pack(side=LEFT)
root.mainloop()
window_design()
我目前收到此错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\cjay2\AppData\Local\Programs\Python\Python35-32\lib\tkinter__init__.py", line 1549, in __call__
return self.func(*args)
TypeError: btn1() missing 2 required positional arguments: 'self' and 'btn1code'
原文由 Eyemsik Cjay 发布,翻译遵循 CC BY-SA 4.0 许可协议
您应该在
button1=Button(root,text="1p",command=btn1)
中使用self.btn1
(btn1
是一个类方法)。btn1()
用一个参数调用,它需要两个参数,将默认值设置为btn1code
或删除它(如果不使用它)。当您在
StringVar()
--- 上调用get()
方法时,它将返回一个字符串,因此您需要在与整数进行比较之前进行转换。要在
label
使用self.result = StringVar()
然后调用self.result.set(a_string)
。检查以下代码: