[英]Tkinter: How to set ttk.Radiobutton activated and get its value?
1) I need to set one of my three ttk.Radiobuttons activated by default when I start my gui app. 1)我需要设置启动我的gui应用时默认激活的三个ttk.Radiobuttons之一。
How do I do it? 我该怎么做?
2) I also need to check if one of my ttk.Radiobuttons was activated/clicked by the user. 2)我还需要检查我的ttk.Radiobuttons是否已被用户激活/单击。
How do I do it? 我该怎么做?
rb1 = ttk.Radiobutton(self.frame, text='5', variable=self.my_var, value=5)
rb2 = ttk.Radiobutton(self.frame, text='10', variable=self.my_var, value=10)
rb3 = ttk.Radiobutton(self.frame, text='15', variable=self.my_var, value=15)
self.rb1.grid(row=0)
self.rb2.grid(row=1)
self.rb3.grid(row=2)
use self.my_var.set(1)
to set the radiobutton with text='5'
as the default RadioButton. 使用self.my_var.set(1)
将text='5'
的单选按钮设置为默认RadioButton。
To get the selected one you have to call a function 要获得所选的对象,您必须调用一个函数
rb1 = ttk.Radiobutton(self.frame, text='5', variable=self.my_var, value=5,command=self.selected)
rb2 = ttk.Radiobutton(self.frame, text='10', variable=self.my_var, value=10,command=self.selected)
rb3 = ttk.Radiobutton(self.frame, text='15', variable=self.my_var, value=15,command=self.selected)
self.rb1.grid(row=0)
self.rb2.grid(row=1)
self.rb3.grid(row=2)
def selected(self):
if self.my_var.get()==5:
"do something"
elif self.my_var.get()==10:
"do something"
else:
"do something"
As for your first question, a convenient and straightforward way is to call the invoke
method: 关于第一个问题,一种方便直接的方法是调用invoke
方法:
rb2.invoke()
Note that this also runs any command
associated with this button. 请注意,这还将运行与此按钮关联的所有command
。
See the Ttk::radiobutton invoke documentation . 请参阅Ttk :: radiobutton调用文档 。
您可以使用rb1.state['selected']
将默认值设置为rb1
并使用self.my_var.get()
获取self.my_var.get()
的值(即文本变量)。
I'm just adding something to Gogo's answer but i can't comment because i don't have enough reputation. 我只是在Gogo的答案中添加了一些内容,但是我没有评论,因为我没有足够的声誉。
Add self.my_var=tk.IntVar()
before the radiobuttons or your program will not know the variable. 在self.my_var=tk.IntVar()
按钮之前添加self.my_var=tk.IntVar()
,否则程序将不知道该变量。 see The Variable Classes for more informations 有关更多信息,请参见变量类 。
for exemple, in my case i need a StringVar(): this works for python 3.* change tkinter
to Tkinter
for python 2 (i'm not 100% sure tho) 例如,在我的情况下,我需要一个StringVar():这适用于python3。*将tkinter
更改为python 2的Tkinter
(我不是100%肯定的吗)
import tkinter as tk
from tkinter import ttk
class XFile_Page(tk.Frame):
...
self.joinType = tk.StringVar()
self.rbLeft = ttk.Radiobutton(self.frameRadioButtons, text='left', variable=self.joinType, value='left',command=self.RadioBtnSelected)
self.rbRight = ttk.Radiobutton(self.frameRadioButtons, text='right', variable=self.joinType, value='right',command=self.RadioBtnSelected)
self.rbLeft.grid(row=0)
self.rbRight.grid(row=1)
#select the rbLeft radiobutton
self.rbLeft.invoke()
def RadioBtnSelected(self):
print(self.joinType.get())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.