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 Python Tkinter dialog box control

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

Share

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

This article mainly explains "how to use Python Tkinter dialog control". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let the editor take you to learn how to use the Python Tkinter dialog control.

In addition to the basic controls, Tkinter provides three dialog box controls:

File selection dialog box: filedailog

Color selection dialog box: colorchooser

Message dialog box: messagebox

File selection dialog box

File dialog box is often used in GUI programs, such as uploading a document needs to select a file locally, including file opening and saving functions need a file dialog box to achieve. The Tkinter provides file dialog box is encapsulated in the tkinter.filedailog module, which provides common functions about file dialog boxes, and the following are frequently used:

The method explains that Open () opens a file SaveAs () opens a dialog box to save files askopenfilename () opens a file, and uses the path of the package file name as the return value askopenfilenames () to open multiple files at the same time, and returns multiple file names askopenfile () as tuples to open files, and returns the file stream object askopenfiles () to open multiple files. And return multiple file stream objects in the form of a list asksaveasfilename () choose what file name to save the file, and return the file name asksaveasfile () choose what type to save the file, and return the file stream object askdirectory selection directory and return the directory name

The common parameter values for the above methods are as follows:

Parameter description defaultextension specifies the suffix name of the file, and the file name is automatically added when the file is saved. If the file suffix name is automatically added, this option value will not take effect. Filetypes specifies the drop-down menu option for filtered file types, which is a list of binary ancestors, where each binary ancestor consists of two parts (type name, suffix). For example, filetypes = [("PNG", "* .png"), ("JPG", "* .jpg"), ("GIF", "* .gif"), ("text file", "* .txt").] initialdir specifies the default path for opening / saving files, and the default path is the current folder parent. If you do not specify this option, the dialog box is displayed on the root window by default. By setting this parameter, the dialog box can be displayed on the child window. Title specifies the title of the file dialog box.

Let's take a look at a group of specific example applications:

From tkinter import * import tkinter.filedialog # Note the number of times to import the file dialog # define a related function def askfile (): # Select a file locally And return the directory of the file filename = tkinter.filedialog.askopenfilename () if filename! ='': lb.config (text= filename) else: lb.config (text=' you did not select any file') root = Tk () root.config (bg='#87CEEB') root.title ("C language Chinese website") root.geometry ('400x200x300) root.iconbitmap (' C:/Users/Administrator/Desktop/C language Chinese logo.ico') btn=Button (root) Text=' Select File', relief=RAISED,command=askfile) btn.grid (row=0,column=0) lb = Label (root,text='',bg='#87CEEB') lb.grid (row=0,column=1,padx=5) # display window root.mainloop ()

The result of running the program:

Figure 1: file selection interface

Let's take a look at another set of sample code for "Save File" as follows:

Import tkinter as tkfrom tkinter import filedialogfrom PIL import Imagedef open_img (): try: global img filepath = filedialog.askopenfilename () # Open the file Return the full path to the file filename.set (filepath) img = Image.open (filename.get ()) except Exception as e: print ("you did not select any file", e) def save_png (): try: filetypes = [("PNG", "* .png"), ("JPG", "* .jpg"), ("GIF", "* .gif"), ("txt files") "* .txt"), ('All files','*')] # returns a pathname file path string If canceled or closed, an empty character is returned. It is a matter for the subsequent code to return the operation of the file. # the function knowledge returns the file name of the selected file. Do not have the ability to save files filenewpath= filedialog.asksaveasfilename (title=' save files', filetypes=filetypes, defaultextension='.png' Initialdir='C:/Users/Administrator/Desktop') path_var.set (filenewpath) # Save file img.save (str (path_var.get () except Exception as e: print (e) window = tk.Tk () window.title ("C language Chinese website") window.geometry ('400x200x300x300' ) window.iconbitmap ('C:/Users/Administrator/Desktop/ C language Chinese logo.ico') filename = tk.StringVar () path_var = tk.StringVar () # define the component to read the file entry = tk.Entry (window Textvariable=filename) entry.grid (row=1, column=0, padx=5, pady=5) tk.Button (window, text=' Select File', command=open_img) .grid (row=1, column=1, padx=5, pady=5) # defines the component entry1 = tk.Entry (window, textvariable=path_var) entry1.grid (row=2, column=0, padx=5, pady=5) tk.Button (window, text=' Save File', command=save_png) .grid (row=2, column=1, padx=5, pady=5) window.mainloop ()

The result of running the program:

Figure 2: program running result

Color selection dialog box

The color selection dialog box (colorchooser) provides a very friendly color panel that allows users to choose the colors they want. When the user selects a color on the panel and presses the OK button, it returns a binary ancestor with the first element being the selected RGB color value and the second element being the corresponding hexadecimal color value.

Color selection dialog is mainly used in brushes, graffiti and other functions, through it can draw colorful colors, the use of this dialog box is very simple, there are mainly the following two common methods:

Method description askcolor () opens a color dialog box and returns the color values selected by the user in the form of tuples (do not choose to return None). The format is ((R, G, B), "# rrggbb") Chooser () opens a color dialog box, and after the user selects a color to determine, returns a two-tuple in the format ((R, G, B), "# rrggbb")

The parameter values of the commonly used color dialog box are shown in the following table:

Property describes the initial color to be displayed by default. The default color is light gray (light gray) title specifies the text of the title bar of the color picker, and the default title is "Color" parent1. If this option is not specified, the dialog box is displayed on the root window by default

two。 If you want to display the dialog box on a child window, you can set the parent = child window object

Let's look at a set of simple usage examples:

Import tkinter as tkfrom tkinter import colorchooserroot = tk.Tk () root.title ("color selection") root.geometry ('400x200mm 300mm 300') root.iconbitmap (' C:/Users/Administrator/Desktop/ C language Chinese logo.ico') def callback (): # Open color dialogue section colorvalue = tk.colorchooser.askcolor () # after clicking OK in the color panel Will display the binary color value lb.config (text=' color value:'+ str (colorvalue)) lb=tk.Label (root,text='',font= ('Verdana', 10)) # place the label tag in the main window lb.pack () tk.Button (root,text= "click to select color", command=callback, width=10, bg='#9AC0CD'). Pack () # display interface root.mainloop ()

The color dialog box is as follows:

Figure 3:tkinter color dialog box

The running results of the above programs are as follows:

Figure 4: running result of the program

Message dialog box

With regard to the message conversation model (messagebox), which has been used in the previous introduction of other controls, it is only briefly introduced in this section.

Message dialog box mainly plays the role of information prompt, warning, description, inquiry, etc., usually used with the "event function", such as performing an operation with an error, and then pop up an error message prompt box. Through the use of message dialog box can improve the user's interactive experience, but also make the GUI program more user-friendly. The message dialog box mainly contains the following common methods:

Method description askokcancel (title=None, message=None) opens a "OK / cancel" dialog askquestion (title=None, message=None) opens a "Yes / No" dialog box. Askretrycancel (title=None, message=None) opens a "retry / cancel" dialog askyesno (title=None, message=None) opens a "Yes / No" dialog showerror (title=None, message=None) opens an error prompt dialog showinfo (title=None, message=None) opens an information prompt dialog box showwarning (title=None, message=None) opens a warning dialog box

The above methods have the same option parameters, as shown in the following table:

Property description default1. Set the default button (that is, press the enter response button)

two。 The default is the first button (like OK, Yes, or retry)

3. Depending on the dialog function, you can choose CANCEL,IGNORE,OK,NO,RETRY or YESicon1. Specify the icon displayed in the dialog box

two。 The values you can specify are: ERROR,INFO,QUESTION or WARNING

3. Note: you cannot specify your own icon parent1. If this option is not specified, the dialog box is displayed on the root window by default

two。 If you want to display the dialog box on a child window, you can set the parent= child window object

The return value of the above methods is usually a Boolean value, or "YES", "NO", "OK" and so on. These methods are relatively easy to use. Instead of enumerating them one by one here, you can see a simple example:

Import tkinter.messageboxresult=tkinter.messagebox.askokcancel ("prompt", "are you sure you want to close the window?") # returns the Boolean parameter print (result)

The result of running the program:

Figure 5: message dialog box

At this point, I believe you have a deeper understanding of "how to use Python Tkinter dialog control". 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