我已重写了此link中显示的示例!
代码如下所示:
from tkinter import *
def sel():
if var.get()==1:
area.delete(1.0, END)
area.insert(END, "Bienvenue")
elif var.get()==2:
area.delete(1.0, END)
area.insert(END, "Welcome")
else:
selection = "You selected the option " + str(var.get())
label.config(text = selection)
area.delete(1.0, END)
area.insert(END,selection)
root = Tk()
area = Text(root)
area.pack()
var = IntVar()
R1 = Radiobutton(root, text="Option 1", variable=var, value=1,
command=sel)
R1.pack(anchor=W)
R2 = Radiobutton(root, text="Option 2", variable=var, value=2,
command=sel)
R2.pack(anchor=W)
R3 = Radiobutton(root, text="Option 3", variable=var, value=3,
command=sel)
R3.pack(anchor=W)
label = Label(root)
label.pack()
root.mainloop()
像这样,代码将在文本小部件中按照radiobutton值输入消息。 示例:如果选择了option1,我将在文本小部件中显示消息“bienvenue”。
但是当我想把这个代码放在一个类对象中时,我的结果却不一样;这是代码:
from tkinter import *
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
m1 = PanedWindow()
m1.pack(fill=BOTH, expand=1)
""" La fenétre principale"""
self.parent.title("Agent")
self.pack(fill=BOTH, expand=1)
area = Text(m1)
area.pack()
global var
var = IntVar()
R1 = Radiobutton(m1, text="Option 1", variable=var, value=1,
command=self.sel(area))
R1.pack(anchor=W)
R2 = Radiobutton(m1, text="Option 2", variable=var, value=2,
command=self.sel(area))
R2.pack(anchor=W)
R3 = Radiobutton(m1, text="Option 3", variable=var, value=3,
command=self.sel(area))
R3.pack(anchor=W)
label = Label(self)
label.pack()
def sel(self,area):
if var.get()==1:
area.delete(1.0, END)
area.insert(END, "Bienvenue")
elif var.get()==2:
area.delete(1.0, END)
area.insert(END, "Welcome")
else:
selection = "You selected the option " + str(var.get())
#label.config(text = selection)
area.delete(1.0, END)
area.insert(END,selection)
def main():
root = Tk()
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
当我使用类对象时,我不确定我做错了什么。那么请你帮我解决一下。
答案 0 :(得分:1)
问题在于这一行(和其他两个按钮类似):
R2 = Radiobutton(m1, text="Option 2", variable=var, value=2,
command=self.sel(area))
通过执行command=self.sel(area)
,您将command
设置为正在执行 self.sel(area)
的结果,即None
而不是方法self.sel
本身。
相反,我建议您在所有代码中将area
更改为self.area
,并从sel
方法中删除其他参数。
def initUI(self):
...
self.area = Text(m1)
...
R1 = Radiobutton(m1, text="Option 1", variable=var, value=1,
command=self.sel)
...
def sel(self):
if var.get()==1:
self.area.delete(1.0, END)
...
...