文章更新于:2020-02-19
待翻译跟进
In this part of the Tkinter tutorial, we will cover some basic Tkinter widgets. We work with the following widgets: Checkbutton, Label, Scale, and Listbox.
Widgets are basic building blocks of a GUI application. Over the years, several widgets became a standard in all toolkits on all OS platforms; for example a button, a check box or a scroll bar. Some of them might have different names. For instance, a check box is called a check button in Tkinter. Tkinter has a small set of widgets which cover basic programming needs. More specialised widgets can be created as custom widgets.
Tkinter Checkbutton
Checkbutton is a widget that has two states: on and off. The on state is visualized by a check mark. (Some themes may have different visuals.) It is used to denote some boolean property. The Checkbutton widget provides a check box with a text label.
#!/usr/bin/env python3
"""
ZetCode Tkinter tutorial
This program toggles the title of the
window with the Checkbutton widget.
Author: Jan Bodnar
Last modified: April 2019
Website: www.zetcode.com
"""
from tkinter import Tk, Frame, Checkbutton
from tkinter import BooleanVar, BOTH
class Example(Frame):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.master.title("Checkbutton")
self.pack(fill=BOTH, expand=True)
self.var = BooleanVar()
cb = Checkbutton(self, text="Show title",
variable=self.var, command=self.onClick)
cb.select()
cb.place(x=50, y=50)
def onClick(self):
if self.var.get() == True:
self.master.title("Checkbutton")
else:
self.master.title("")
def main():
root = Tk()
root.geometry("250x150+300+300")
app = Example()
root.mainloop()
if __name__ == '__main__':
main()