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 use the Tkinter method of python

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

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to use the Tkinter method of python". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use python's Tkinter method.

Introduction 1.1.What is Tkinter

Tkinter is a module that uses python to design windows. The Tkinter module ("Tk interface") is the interface of Python's standard Tk GUI toolkit. As a python-specific GUI interface, is an image window, tkinter is python's own, can be edited GUI interface, used to get started, familiar with the use of windows, it is very necessary.

II. Preparation work 2.1.Establishment of Windows demonstration environment

Install the python3.7 installation editor and demonstrate the Visual Studio Code you are using

3. Tkinter create window 3.1, create a window

First, we import tkinter's library.

Import tkinter as tk # imports the library into the code and gives it an alias. Later, the code will use this alias root = tk.Tk () # this library has the method Tk (). The purpose of this method is to create a window.

If you just execute the above two sentences of code, there will be no response to the running program, because there is only one main function, which will be gone after execution from top to bottom, and the window will disappear very quickly, so now all we have to do is keep the window displayed, so we can add a loop.

The name of the window created is root, so we can use this root to manipulate the window later.

Root.mainloop () # add this sentence and you can see the window.

By executing the above three sentences of code, we can see the window.

Give the window a title root.title ('demo window')

3.3, window Settin

With the following code, we can set the length and width of the window and its position on the screen

Root.geometry ("300x100+630+80") # length x width + x width

Create a button and add a click event to the button

There is a method Button () in this library, and as long as we call this method, we can create this component, and we assign this component to a constant, and then we can use this constant to manipulate the button. The parameter in this method is to write the name of the window Button (root), which means to put the button we created on top of this window.

Btn1 = tk.Button (root)

Give the button a name

Btn1 ["text"] = "Click"

The button component we created has already been placed in the window, but where it is placed in the window, where it is in the east, south, west, east and west, we can use pack () to locate (other positioning methods will be introduced later)

The positioning of the btn1.pack () # button in the window

To create a pop-up window for click-button events, import messagebox first. This must be imported separately.

From tkinter import messageboxdef test (e): messagebox.showinfo ("window name", "Click success")

Now that I have the button and the method, what I want to do is click the button and execute this method, so I need to bind the button to the method

Btn1.bind ("", test) # the first parameter is the event of pressing the left mouse button, and the second parameter is the name of the method to be executed

There is a method bind () in the button component that binds.

Complete code

Import tkinter as tkfrom tkinter import messageboxroot = tk.Tk () # create window root.title ('demo window') root.geometry ("300x100+630+80") # length x width + x*ybtn1 = tk.Button (root) # create button And put the button in the window btn1 ["text"] = "Click" # give the button a name btn1.pack () # Button layout def test (e):''create pop-up window' 'messagebox.showinfo ("window name", "click successful") btn1.bind ("", test) # bind the button to the method, that is, create an event root.mainloop () # to keep the window displayed. Cycle

3.4. Layout of components within the window

Three layout managers: pack-grid-place

Pack

This layout manager arranges components either vertically or horizontally

Grid

The Grid layout manager places the controls in a two-dimensional table.

The main control is divided into a series of rows and columns, and each cell in the table can place a control.

The option describes the column number of the column cell, the number of columns spanned by positive integers columnspan starting from 0, the number of columns spanned by positive integers row cells, the number of rows spanned by positive integers rowspan from 0, the number of rows spanned, positive integers ipadx, ipady sets the interval between subcomponents, x direction or y direction, the default unit is pixel, non-floating point number, the interval between components juxtaposed with pady, x direction or y direction The default unit is pixels, not floating-point numbers. The default 0.0sticky component clings to one foot of the cell in which it is located, corresponding to the east, south, west, west, and four corners. East = "e", south = "s", west = "w", north = "n", "ne", "se", "sw", "nw"

Grid_info () view the default parameters of the component

Import tkinter as tkroot = tk.Tk () # default button btn1 = tk.Button (root) btn1 ["text"] = "Button 1" btn1.grid () print (btn1.grid_info () root.title ('demo window') root.geometry ("300x150+1000+300") root.mainloop ()

Column specifies the column in which the control resides

Import tkinter as tkroot = tk.Tk () # button 1btn1 = tk.Button (root) btn1 ["text"] = "button 1" btn1.grid (column=0) # button 2btn2 = tk.Button (root) btn2 ["text"] = "button 2" btn2.grid (column=1) root.title ('demo window') root.geometry ("300x100+1000+300") root.mainloop ()

Columnspan specifies the number of columns that each control spans. What is columnspan?

Merged cells similar to excel

An occupies the width of two grids, and colunmspan is 2.

````pythonimport tkinter as tkroot = tk.Tk () # button 1btn1 = tk.Button (root) btn1 ["text"] = "button 1" btn1.grid (column=0, columnspan=2) # button 2btn2 = tk.Button (root) btn2 ["text"] = "button 2" btn2.grid (column=1, columnspan=1) root.title ('presentation window') root.geometry ("300x100+1000+300") root.mainloop ()

Row specifies the row where the control is located

Import tkinter as tkroot = tk.Tk () # Button 1btn1 = tk.Button (root) btn1 ["text"] = "Button 1" btn1.grid (row=0) # Button 2btn2 = tk.Button (root) btn2 ["text"] = "Button 2" btn2.grid (row=1) # Button 3btn3 = tk.Button (root) btn3 ["text"] = "Button 2" btn3.grid (row=2) root.title ('presentation window') root.geometry ("300x100+1000+300") root.mainloop ()

Rowspan specifies the number of rows that each control spans

What is rowspan?

Merged cells similar to excel

An occupies the height of two grids, and rowspan is 2.

Import tkinter as tkroot = tk.Tk () # button 1btn1 = tk.Button (root) btn1 ["text"] = "button 1" btn1.grid (row=0, rowspan=2) # button 2btn2 = tk.Button (root) btn2 ["text"] = "button 2" btn2.grid (row=2, rowspan=1) root.title ('presentation window') root.geometry ("300x100+1000+300") root.mainloop ()

Ipadx horizontal inner margin

Import tkinter as tkroot = tk.Tk () # button 1btn1 = tk.Button (root) btn1 ["text"] = "button 1" btn1.grid (ipadx=20) # button 2btn2 = tk.Button (root) btn2 ["text"] = "button 2" btn2.grid (ipadx=5) root.title ('demo window') root.geometry ("300x100+1000+300") root.mainloop ()

Ipady Vertical Inner margin

Import tkinter as tkroot = tk.Tk () # button 1btn1 = tk.Button (root) btn1 ["text"] = "button 1" btn1.grid (ipady=20) # button 2btn2 = tk.Button (root) btn2 ["text"] = "button 2" btn2.grid (ipady=5) root.title ('demo window') root.geometry ("300x150+1000+300") root.mainloop ()

Padx horizontal outer margin

Import tkinter as tkroot = tk.Tk () # button 1btn1 = tk.Button (root) btn1 ["text"] = "button 1" btn1.grid (padx=50) # button 2btn2 = tk.Button (root) btn2 ["text"] = "button 2" btn2.grid (column=1, padx=20) root.title ('demo window') root.geometry ("300x150+1000+300") root.mainloop ()

Pady vertical outer margin

Import tkinter as tkroot = tk.Tk () # button 1btn1 = tk.Button (root) btn1 ["text"] = "button 1" btn1.grid (pady=30) # button 2btn2 = tk.Button (root) btn2 ["text"] = "button 2" btn2.grid (pady=20) root.title ('demo window') root.geometry ("300x150+1000+300") root.mainloop ()

The direction of sticky components east, south, west and west

Import tkinter as tkroot = tk.Tk () # default button btn1 = tk.Button (root) btn1 ["text"] = "default button demonstration effect" btn1.grid (ipadx=50) # button 2btn2 = tk.Button (root) btn2 ["text"] = "button 2" btn2.grid (row=1, sticky= "w") # button 3btn3 = tk.Button (root) btn3 ["text"] = "button 3" btn3.grid (row=1 Sticky= "e") root.title ('demo window') root.geometry ("300x150+1000+300") root.mainloop ()

Place layout Manager

The place layout manager can precisely control the location of components through coordinates, which is suitable for some scenes with more flexible layout.

The option describes the absolute coordinates of the upper left corner of the rely y component (equivalent to the window) relx, the coordinates of the upper left corner of the height component (relative to the parent container) width, the width and height of the relheight component relwidth, the width and height of the relheight component (relative to the parent container) anchor alignment, left alignment "w", right alignment "e", top alignment "n" Bottom align "s" import tkinter as tkroot = tk.Tk () but1 = tk.Button (root, text= "Button 1") but1.place (relx=0.2, Xerox 100, YP20, relwidth=0.2, relheight=0.5) root.title ('demo window') root.geometry ("300x150+1000+300") root.mainloop ()

4. The introduction of Tkinter basic controls. Package import tkinter as tkclass GUI: def _ _ init__ (self): self.root = tk.Tk () self.root.title ('demo window') self.root.geometry ("500x200+1100+150") self.interface () def interface (self): "interface writing location" passif _ _ name__ = ='_ _ main__': a " = GUI () a.root.mainloop () 4.2, Text display _ Label def interface (self): "interface writing location" self.Label0 = tk.Label (self.root) " Text= "text display") self.Label0.grid (row=0, column=0) 4.3.Button display _ Button def interface (self): "Interface Writing location"self.Button0 = tk.Button (self.root, text=" Button display ") self.Button0.grid (row=0) Column=0) 4.4.4.The input box shows _ Entry def interface (self): "self.Entry0 = tk.Entry (self.root) self.Entry0.grid (row=0, column=0) 4.5, the text input box shows _ Text# pack layout def interface (self):" interface writing location "" self.w1 = tk.Text (self.root, width=80) " Height=10) self.w1.pack (pady=0, padx=30) # grid layout def interface (self): "Interface Writing location" self.w1 = tk.Text (self.root, width=80, height=10) self.w1.grid (row=1, column=0) 4.6, check button _ Checkbutton def interface (self): "Interface Writing location"self.Checkbutton01 = tk.Checkbutton (self.root)" Text= "name") self.Checkbutton01.grid (row=0, column=2) 4.7, radio button _ Radiobutton def interface (self): "interface writing location"self.Radiobutton01 = tk.Radiobutton (self.root, text=" name ") self.Radiobutton01.grid (row=0) Column=2) 5. Introduction to component usage 5.1.Button (Button) binding event def interface (self): "interface writing location"self.Button0 = tk.Button (self.root, text=" run ", command=self.event) self.Button0.grid (row=0, column=0) self.Button1 = tk.Button (self.root, text=" exit ", command=self.root.destroy) Bg= "Gray") # bg= Color self.Button1.grid (row=0, column=1, sticky= "e" Ipadx=10) def event (self): "button event"print (" run successfully ") 5.2, input box (Entry) content acquisition def interface (self):" interface writing location "self.entry00 = tk.StringVar () self.entry00.set (" default information ") self.entry0 = tk.Entry (self.root) Textvariable=self.entry00) self.entry0.grid (row=1, column=0) self.Button0 = tk.Button (self.root, text= "run", command=self.event) self.Button0.grid (row=0, column=0) def event (self): "button event, get text message"a = self.entry00.get () print (a) 5.2, text input box (Text) Write text messages and clear text messages def interface (self): "self.Button0 = tk.Button (self.root, text=" clear, command=self.event) self.Button0.grid (row=0, column=0) self.w1 = tk.Text (self.root, width=80, height=10) self.w1.grid (row=1, column=0) self.w1.insert ("insert") "default information") def event (self):''clear the input box' 'self.w1.delete (1. 0, "end") 5.3, get the status of the check button (Checkbutton) def interface (self): "interface writing location"self.Button0 = tk.Button (self.root, text=" OK, command=self.event) self.Button0.grid (row=0) Column=0) self.v1 = tk.IntVar () self.Checkbutton01 = tk.Checkbutton (self.root, text= "check box", command=self.Check_box, variable=self.v1) self.Checkbutton01.grid (row=1, column=0) self.w1 = tk.Text (self.root, width=80, height=10) self.w1.grid (row=2, column=0) def event (self):''button event Gets the status of the check box. 1 indicates that it is checked. 0 means''a = self.v1.get () self.w1.insert (1. 0, str (a) +'\ n') def Check_box (self):''checkbox event''if self.v1.get () = = 1: self.w1.insert () "check" +'\ n') else: self.w1.insert (1. 0, "unchecked" +'\ n') 5.4.Clearing the control def interface (self): "interface writing location"self.Button0 = tk.Button (self.root, text=" OK ", command=self.event) self.Button0.grid (row=0) Column=0) self.Label0 = tk.Label (self.root, text= "text display") self.Label0.grid (row=1, column=0) self.Entry0 = tk.Entry (self.root) self.Entry0.grid (row=2, column=0) self.w1 = tk.Text (self.root, width=80, height=10) self.w1.grid (row=3, column=0) def event (self):''button event Clear Label, Entry, Text components''a = [self.Label0, self.Entry0, self.w1] for i in a: i.grid_forget () 5.5.Clearing check box check status def interface (self): "interface writing location" self.Button0 = tk.Button (self.root, text= "OK", command=self.event) self.Button0.grid (row=0) Column=0) self.v1 = tk.IntVar () self.Checkbutton01 = tk.Checkbutton (self.root, text= "check box", command=self.Check_box, variable=self.v1) self.Checkbutton01.grid (row=1, column=0) self.w1 = tk.Text (self.root, width=80, height=10) self.w1.grid (row=2, column=0) def event (self):''button event Clear the check box to check the status''self.Checkbutton01.deselect () def Check_box (self):' 'check box event' if self.v1.get () = = 1: self.w1.insert (1. 0, "check" +'\ n') else: self.w1.insert (1. 0) "unchecked" +'\ n') 5.6. text box (Text) content acquisition def interface (self): "interface writing location"self.Button0 = tk.Button (self.root, text=" OK ", command=self.event) self.Button0.grid (row=0, column=0) self.w1 = tk.Text (self.root, width=80, height=10) self.w1.grid (row=1) Column=0) def event (self): a = self.w1.get ('0.02,' end') print (a) VI. Tkinter uses multithreading 6.1, why use multithreading

The following is a single-thread run

Def interface (self): "interface writing location"self.Button0 = tk.Button (self.root, text=" OK ", command=self.event) self.Button0.grid (row=0, column=0) self.w1 = tk.Text (self.root, width=80, height=10) self.w1.grid (row=1, column=0) def event (self):''button event Always cycle''a = 0 while True: a + = 1 self.w1.insert (1. 0, str (a) +'\ n')

In a single thread, the main thread needs to run the window. If the "OK" button is clicked at this time, the main thread will execute the event method, and the interface will appear "unresponsive". If we want the interface to display normally, we need to use multithreading (threading).

Multithreaded, complete code

Import tkinter as tkimport threading # Import multithreaded module class GUI: def _ _ init__ (self): self.root = tk.Tk () self.root.title ('demo window') self.root.geometry ("500x200+1100+150") self.interface () def interface (self): "interface writing location"self.Button0 = tk.Button (self.root, text=" OK " Command=self.start) self.Button0.grid (row=0, column=0) self.w1 = tk.Text (self.root, width=80, height=10) self.w1.grid (row=1, column=0) def event (self):''button event Always loop''a = 0 while True: a + = 1 self.w1.insert (1. 0, str (a) +'\ n') def start (self): self.T = threading.Thread (target=self.event) # multithreaded self.T.setDaemon (True) # thread daemon, that is, after the main process ends, the thread also ends. Otherwise, the main process terminates the child process without ending self.T.start () # starting if _ _ name__ = ='_ main__': a = GUI () a.root.mainloop ()

7. Tkinter multithreading pauses and resumes import tkinter as tkimport threadingfrom time import sleepevent = threading.Event () class GUI: def _ _ init__ (self): self.root = tk.Tk () self.root.title ('demo window') self.root.geometry ("500x200+1100+150") self.interface () def interface (self): "Interface Writing location"self.Button0 = tk.Button (self.root)" Text= "start", command=self.start) self.Button0.grid (row=0, column=0) self.Button0 = tk.Button (self.root, text= "pause", command=self.stop) self.Button0.grid (row=0, column=1) self.Button0 = tk.Button (self.root, text= "continue", command=self.conti) self.Button0.grid (row=0, column=2) self.w1 = tk.Text (self.root, width=70 Height=10) self.w1.grid (row=1, column=0, columnspan=3) def event (self):''button event Always cycle''while True: sleep (1) event.wait () self.w1.insert 'running' def start (self): event.set () self.T = threading.Thread (target=self.event) self.T.setDaemon (True) self.T.start () def stop (self): event.clear () self.w1.insert 'pause' +'\ n') def conti (self): event.set () self.w1.insert (1.0,' continue'+'\ n') if _ _ name__ = ='_ _ main__': a = GUI () a.root.mainloop () VIII, call between Tkinter files 8.1, preparation

A.py file-interface logic + thread b.py file-business logic above files are in the same directory

8.2 、 Method # a.py file import tkinter as tkimport threadingfrom b import logic # calls the logic class class GUI in file b: def _ _ init__ (self): self.root = tk.Tk () self.root.title ('demo window') self.root.geometry ("500x260+1100+150") self.interface () def interface (self): "interface writing location" "self.Button0 = tk.Button (self.root Text= "confirm execution", command=self.start, bg= "# 7bbfea") self.Button0.grid (row=0, column=1, pady=10) self.entry00 = tk.StringVar () self.entry00.set ("") self.entry0 = tk.Entry (self.root, textvariable=self.entry00) self.entry0.grid (row=1, column=1, pady=15) self.w1 = tk.Text (self.root, width=50, height=8) self.w1.grid (row=2, column=0, columnspan=3 Padx=60) def seal (self):''write a separate method for the class of the b file' a = self.entry00.get () W1 = self.w1 logic () .event (a, W1) def start (self):''the child thread cannot directly execute the class of b You need to write a separate method for the b file Then execute''self.T = threading.Thread (target=self.seal) self.T.setDaemon (True) self.T.start () if _ _ name__ =' _ _ main__': a = GUI () a.root.mainloop () # b.py file import timeclass logic (): def _ init__ (self): pass def main (self, a X): while True: y = int (a) + int (x) self.w1.insert (1.0, str (y) +'\ n') time.sleep (1) x + = 1 def event (self, a, W1): 'call main's method' 'self.w1 = W1 x = 1 self.main (a, x) so far I believe you have a deeper understanding of "how to use python's Tkinter method", so you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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