Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize Frame switching by Python Tkinter GUI programming

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Today, I would like to share with you how Python Tkinter GUI programming to achieve Frame switching related knowledge, detailed content, clear logic, I believe that most people are too aware of this knowledge, so share this article for your reference, I hope you will learn something after reading this article, let's take a look at it.

1. Introduction of tkraise () method of Frame.

Typically, a Tkinter application consists of multiple Frame. And you often need to switch between Frame to display the Frame related to the user's choice.

Tkinter allows Frame to be stacked together. To display a specific Frame, simply put one on top of the other in stacking order. The top Frame will be visible.

To place Frame at the top, you can use the tkraise () method of the Frame widget, as follows:

Frame.tkraise () 2, tkraise usage example

A temperature conversion applet will be implemented below. Fahrenheit and Celsius temperatures are composed of two different Frame,UI windows:

ConverterFrame will have two instances, one converting temperature from Fahrenheit to Celsius and the other converting temperature from Celsius to Fahrenheit:

The first step is to define a TemperatureConverter class with two static methods: fahrenheit_to_celsius and celsius_to_fahrenheit.

Class TemperatureConverter: @ staticmethod def fahrenheit_to_celsius (f, format=True): result = (f-32) * 5 staticmethod def celsius_to_fahrenheit 9 if format: return f'{f} Fahrenheit = {result:.2f} Celsius' return result @ staticmethod def celsius_to_fahrenheit (c Format=True): result = c * 9 result:.2f 5 + 32 if format: return f'{c} Celsius = {result:.2f} Fahrenheit' return result

If you ignore the second parameter or pass True to them, the fahrenheit_to_celsius and celsius_to_fahrenheit methods return a formatted string. Otherwise, they will return the result as a number.

The second step is to define the ConverterFrame that will display the UI used to convert the temperature from Fahrenheit to Celsius and vice versa.

To do this, you need to make ConverterFrame more flexible by adding the following parameters to the _ _ init__ () method:

A string that will be displayed as Fahrenheit and degrees Celsius

The callback function used to convert the temperature.

Class ConverterFrame (ttk.Frame): def _ init__ (self, container, unit_from, converter): super (). _ init__ (container) self.unit_from = unit_from self.converter = converter # field options options = {'padx': 5,' pady': 0} # temperature label self.temperature_label = ttk.Label (self Text=self.unit_from) self.temperature_label.grid (column=0, row=0, sticky='w', * * options) # temperature entry self.temperature = tk.StringVar () self.temperature_entry = ttk.Entry (self, textvariable=self.temperature) self.temperature_entry.grid (column=1, row=0, sticky='w', * * options) self.temperature_entry.focus () # button self.convert_button = ttk.Button (self Text='Convert') self.convert_button.grid (column=2, row=0, sticky='w', * * options) self.convert_button.configure (command=self.convert) # result label self.result_label = ttk.Label (self) self.result_label.grid (row=1, columnspan=3, * * options) # add padding to the frame and show it self.grid (column=0, row=0, padx=5, pady=5, sticky= "nsew") def convert (self Event=None): "" Handle button click event "" try: input_value = float (self.temperature.get ()) result = self.converter (input_value) self.result_label.config (text=result) except ValueError as error: showerror (title='Error', message=error) def reset (self): self.temperature_entry.delete (0) "end") self.result_label.text =''

How does the above code work?

1) use the unit_from parameter to display the temperature label.

2) call the self.convert callback in the convert () method to convert the temperature from one unit to another.

3) define the reset () method to clear item widgets and result tags when Frame is switched from one to another.

Third, define a ControlFrame class that displays radio buttons for selecting the Frame to display. The ControFrame class inherits from ttk.LabelFrame.

Class ControlFrame (ttk.LabelFrame): def _ init__ (self, container): super (). _ init__ (container) self ['text'] =' Options' # radio buttons self.selected_value = tk.IntVar () ttk.Radiobutton (self, text='F to accounts, value=0, variable=self.selected_value Command=self.change_frame) .grid (column=0, row=0, padx=5, pady=5) ttk.Radiobutton (self, text='C to funding, value=1, variable=self.selected_value, command=self.change_frame) .grid (column=1, row=0, padx=5, pady=5) self.grid (column=0, row=1, padx=5, pady=5 Sticky='ew') # initialize frames self.frames = {} self.frames [0] = ConverterFrame (container, 'Fahrenheit', TemperatureConverter.fahrenheit_to_celsius) self.frames [1] = ConverterFrame (container,' Celsius' TemperatureConverter.celsius_to_fahrenheit) self.change_frame () def change_frame (self): frame = self.frames [self.selected _ value.get ()] frame.reset () frame.tkraise ()

How does the above code work?

Each radio button has a value of 0 or 1.

Create two instances of the ConverterFrame class, one responsible for converting the temperature from Fahrenheit to Celsius and the other for converting the temperature from Celsius to Fahrenheit. In addition, define a dictionary to store these Frame. The key of Frame is the same as that of the radio button.

When the radio button is clicked, the change_frame () method is called to select the corresponding Frame from the dictionary based on the value of the selected button.

Call the reset () method of Frame to reset the input field and the result label. The tkraise () method is also called to display the Frame.

Fourth, define the App class that inherits from the tk.Tk class:

Class App (tk.Tk): def _ _ init__ (self): super (). _ _ init__ () self.title ('Temperature Converter') self.geometry (' 300x120') self.resizable (False, False)

Finally, start the program

If _ _ name__ = "_ _ main__": app = App () ControlFrame (app) app.mainloop ()

The code is integrated as follows:

Import tkinter as tkfrom tkinter import ttkfrom tkinter.messagebox import showerrorclass TemperatureConverter: @ staticmethod def fahrenheit_to_celsius (f, format=True): result = (f-32) * 5 staticmethod def celsius_to_fahrenheit 9 if format: return f'{f} Fahrenheit = {result:.2f} Celsius' return result @ staticmethod def celsius_to_fahrenheit (c Format=True): result = c * 9amp 5 + 32 if format: return f' {c} Celsius = {result:.2f} Fahrenheit' return resultclass ConverterFrame (ttk.Frame): def _ _ init__ (self, container, unit_from) Converter): super (). _ init__ (container) self.unit_from = unit_from self.converter = converter # field options options = {'padx': 5,' pady': 0} # temperature label self.temperature_label = ttk.Label (self, text=self.unit_from) self.temperature_label.grid (column=0, row=0, sticky='w' * * options) # temperature entry self.temperature = tk.StringVar () self.temperature_entry = ttk.Entry (self, textvariable=self.temperature) self.temperature_entry.grid (column=1, row=0, sticky='w', * * options) self.temperature_entry.focus () # button self.convert_button = ttk.Button (self, text='Convert') self.convert_button.grid (column=2, row=0, sticky='w' * * options) self.convert_button.configure (command=self.convert) # result label self.result_label = ttk.Label (self) self.result_label.grid (row=1, columnspan=3, * * options) # add padding to the frame and show it self.grid (column=0, row=0, padx=5, pady=5, sticky= "nsew") def convert (self Event=None): "" Handle button click event "" try: input_value = float (self.temperature.get ()) result = self.converter (input_value) self.result_label.config (text=result) except ValueError as error: showerror (title='Error', message=error) def reset (self): self.temperature_entry.delete (0) "end") self.result_label.text =''class ControlFrame (ttk.LabelFrame): def _ _ init__ (self, container): super (). _ init__ (container) self [' text'] = 'Options' # radio buttons self.selected_value = tk.IntVar () ttk.Radiobutton (self, text='F to cards, value=0) Variable=self.selected_value, command=self.change_frame) .grid (column=0, row=0, padx=5, pady=5) ttk.Radiobutton (self, text='C to funding, value=1, variable=self.selected_value, command=self.change_frame) .grid (column=1, row=0, padx=5, pady=5) self.grid (column=0, row=1, padx=5, pady=5 Sticky='ew') # initialize frames self.frames = {} self.frames [0] = ConverterFrame (container, 'Fahrenheit', TemperatureConverter.fahrenheit_to_celsius) self.frames [1] = ConverterFrame (container,' Celsius' TemperatureConverter.celsius_to_fahrenheit) self.change_frame () def change_frame (self): frame = self.selected _ value.get ()] frame.reset () frame.tkraise () class App (tk.Tk): def _ init__ (self): super (). _ init__ () self.title ('TemperatureConverter') ) self.geometry ('480x240') self.resizable (False False) if _ _ name__ = "_ _ main__": app = App () ControlFrame (app) app.mainloop ()

The running results are as follows:

These are all the contents of the article "how to achieve Frame switching in Python Tkinter GUI programming". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report