Mein Beispielcode für Radiobuttons sieht so aus:
Code: Alles auswählen
#!/usr/bin/env python
import Tkinter
import tkMessageBox
class myWindow:
def __init__(self):
self.mw = Tkinter.Tk()
self.mw.option_add("*font", ("Arial", 15, "normal"))
self.mw.geometry("+250+200")
self.colour = Tkinter.Variable()
self.rb1 = Tkinter.Radiobutton(self.mw, text = "Red", variable = self.colour, value = "Red")
self.rb2 = Tkinter.Radiobutton(self.mw, text = "Yellow", variable = self.colour, value = "Yellow")
self.rb3 = Tkinter.Radiobutton(self.mw, text = "Green", variable = self.colour, value = "Green")
self.rb2.select()
self.rb1.pack()
self.rb2.pack()
self.rb3.pack()
self.btn1 = Tkinter.Button(self.mw, text = "Ok", command = self.btnClick)
self.btn1.pack()
self.btn2 = Tkinter.Button(self.mw, text = "Exit", command = self.mw.destroy)
self.btn2.pack()
self.mw.mainloop()
def btnClick(self):
a = self.colour.get()
tkMessageBox.showinfo(title = 'Your selection', message = "The selected colour is: " + a)
if __name__ == "__main__":
app = myWindow()
Und dazu meine Erläuterung:
Radiobuttons are very useful, if the user should make a single choice between several possibilities.
In the script we create three radiobuttons "rb1", "rb2" and "rb3" and sign them with "Red", "Yellow" and "Green" (this could be the selection for a colour of a car for example).
The radiobuttons are connected by sharing the same variable "colour". We have to use a special "Tkinter.Variable"-object for the "colour"-variable.
Passing the "value"-argument, we define, what value should be assigned to the variable "colour", if the radiobutton is selected.
Using the ".select()"-method, we make radiobutton "rb2" the default-selection.
When "btn1" is clicked, the method "btnClick" is run. We need to use the ".get()"-method of the "Tkinter.Variable"-object "colour" to get its value as a Python-string. This value is then displayed in the "tkMessageBox".
HTH