2013-04-11 163 views
0

所以我一直玩python 3.2 tkinter。 今天刚刚发现单选按钮中的文字没有显示在按钮旁边,它只显示“0”。 另外,当我在单选按钮语句末尾有.pack()时,它显示错误'NoneType'对象没有属性'pack'。这很奇怪,是因为他们在新版本中改变了。我是否需要导入其他一些东西?由于python 3.2 tkinter,单选按钮中的文本不显示

from tkinter import* 

class Name: 
    def __init__(self, master): 
     frame = Frame(master) 
     frame.pack() 

     self._var = IntVar() 
     self._fullRadio = Radiobutton(frame, text="yes", textvariable=self._var, value=1) 
     self._fullRadio.grid(row=2, column=0)#.pack() 

     self._partRadio = Radiobutton(frame, text="no", textvariable=self._var, value=2) 
     self._partRadio.grid(row=3)#.pack() 

     self._notRadio = Radiobutton(frame, text="not both", textvariable=self._var, value=3) 
     self._notRadio.grid(row=4)#.pack() 

root = Tk() 
application = Name(root) 
root.mainloop() 

回答

2

你想要的参数variable,不textvariable

from tkinter import* 
class Name: 
    def __init__(self, master): 
     frame = Frame(master) 
     frame.grid() # changed from frame.pack() 

     self._var = IntVar() 
     self._fullRadio = Radiobutton(frame, text="yes", variable=self._var, value=1) 
     self._fullRadio.grid(row=2, column=0) 

     self._partRadio = Radiobutton(frame, text="no", variable=self._var, value=2) 
     self._partRadio.grid(row=3) 

     self._notRadio = Radiobutton(frame, text="not both", variable=self._var, value=3) 
     self._notRadio.grid(row=4) 

root = Tk() 
application = Name(root) 
root.mainloop() 

此外,作为一个经验法则,它不是最好在同一帧混合.grid().pack()

至于你的第二个问题:.grid()是另一个布局管理器。只是在做self._fullRadio.grid(row=2, column=0)已经设置的布局;除了.grid()(在同一对象上),您不需要使用.pack()

由于self._fullRadio.grid(row=2, column=0)返回None(这是一个方法调用),您会收到一个错误消息,NoneType对象没有方法.pack()。坚持要么gridpack,但不是在同一时间。

+0

哈哈,这就是一个愚蠢的错误......感谢您的帮助:) – PyJar 2013-04-11 01:23:28

+1

您可以在同一个应用程序中混合包和网格,只是不在同一个容器(即:不在同一个框架中)。这是因为每个人都会查看小部件大小的变化,并且(可能)会在更改大小时重新调整其管理的所有窗口的大小。那么会发生什么呢,那个网格根据它的规则改变了一些小部件的大小,打包注意到了这些改变,从而根据_its_规则改变了其他小部件的大小。网格注意到所有变化等。然而,在同一个_application_中同时使用grid和pack是Tkinter所有有经验的编程人员所做的。 – 2013-04-11 10:54:39