官术网_书友最值得收藏!

Handling widget-specific variables

You need variables with a wide variety of widgets. You likely need a string variable to track what the user enters into the entry widget or text widget. You most probably need Boolean variables to track whether the user has checked off the Checkbox widget. You need integer variables to track the value entered in a Spinbox or Slider widget.

In order to respond to changes in widget-specific variables, Tkinter offers its own variable class. The variable that you can use to track widget-specific values must be subclassed from this Tkinter variable class. Tkinter offers some commonly used predefined variables. They are StringVar, IntVar, BooleanVar, and DoubleVar.

You can use these variables to capture and play with the changes in the values of variables from within your callback functions. You can also define your own variable type, if required.

Creating a Tkinter variable is simple. You simply have to call the constructor:

my_string = StringVar()
ticked_yes = BooleanVar()
group_choice = IntVar()
volume = DoubleVar()

Once the variable is created, you can use it as a widget option, as follows:

Entry(root, textvariable=my_string)
Checkbutton(root, text="Remember Me", variable=ticked_yes)
Radiobutton(root, text="Option1", variable=group_choice, value="option1") #radiobutton
Scale(root, label="Volume Control", variable=volume, from =0, to=10) # slider

Additionally, Tkinter provides access to the values of variables via the set() and get() methods, as follows:

my_var.set("FooBar") # setting value of variable
my_var.get() # Assessing the value of variable from say a callback

A demonstration of the Tkinter variable class is available in the 1.11.py code file. The code generates a window, as shown in the following screenshot:

This concludes our brief discussion on events and callbacks. Here's a brief summary of the things that we discussed:

  • The command binding, which is used to bind simple widgets to certain functions
  • The use of the lambda function in case you need to process arguments
  • Event binding using the widget.bind(event, callback, add=None) method to bind keyboard and mouse events to your widgets and invoke callbacks when certain events occur
  • The passing of extra arguments to a callback
  • The binding of events to an entire application or to a particular class of widget by using bind_all() and bind_class()
  • Using the Tkinter variable class to set and get the values of widget-specific variables

In short, you now know how to make your GUI program responsive to end-user requests!

主站蜘蛛池模板: 靖安县| 资溪县| 唐山市| 万州区| 聂拉木县| 札达县| 区。| 阿瓦提县| 前郭尔| 宁陵县| 梁河县| 巴彦淖尔市| 台安县| 安图县| 多伦县| 应用必备| 平果县| 社旗县| 资源县| 东乌珠穆沁旗| 沈丘县| 乌鲁木齐县| 武宣县| 肃宁县| 留坝县| 达尔| 慈溪市| 云安县| 资源县| 浦北县| 廉江市| 隆昌县| 香河县| 沂南县| 富顺县| 普宁市| 济阳县| 通江县| 古丈县| 调兵山市| 呼伦贝尔市|