Some very flexible usage methods and utility functions of Python tkinter

Table of contents

1. Hide window maximize and minimize buttons

2. Hide the entire title bar

3. Realize the transparent background and transparent font of the component

4. Make a system prompt

5. Wait for output (wait_window() and other methods)

6. Flexible use of the window update method to replace the mainloop to avoid the use of multi-threading or window after method

7. Disable windows

8. Make the component in the busy state

9. Invoke the font selection dialog

10. Window theme


1. Hide window maximize and minimize buttons

##Example1
from tkinter import *
parent = Tk()
parent.title("parent")

toplevel = Toplevel(parent)
toplevel.title("toplevel")
toplevel.transient(parent)#实现messagebox式的窗口
mainloop()
​#这里需要注意的是,当父窗口隐藏后,经过transient简化的窗口也会跟随父窗口隐藏。

##Example2
from tkinter import *
root = Tk()
root.title("Tk")
toplevel = Toplevel(root)
toplevel.title("Toplevel")
root.attributes("-toolwindow", True)
toplevel.attributes("-toolwindow", True)#实现menu点击虚线(tearoff)后的窗口效果
mainloop()

2. Hide the entire title bar

from tkinter import *
parent = Tk()
Toplevel(parent).overrideredirect(True)#实现隐藏了整个标题栏的窗口
mainloop()

3. Realize the transparent background and transparent font of the component

If you want to make all components in the entire window transparent (adjustable transparency), you can use Tk/Toplevel.attributes("-alpha", alphanum) see: https://www.pynote.net/archives /1234

If you want to set the transparent background of the component to make the font transparent, you can use Tk()/Toplevel().attributes("-transparentcolor",colorname)

It should be noted that in Windows7, transparent content cannot be penetrated by mouse clicks, and users cannot click other applications in the transparent area. But in Windows 10, the user is ok. On other systems, transparentcolor may not be enforced.

from tkinter import *

root = Tk()
root.attributes("-transparentcolor", "white")#此处将white颜色设置为透明,可以替换不同的颜色。
Label(root, text="背景透明", bg="white").pack()#把已经变成透明色的白色设置为背景。

mainloop()

4. Make a system prompt

from tkinter import *
root = Tk()
root.bell()#系统提示音

When making an application, the bell method can be set to be executed when the user operation fails.

5. Wait for output (wait_window() and other methods)

tkinter components are usually drawn together on the window, if you want to wait for part of the drawing, you can use the wait_window(), wait_visibility() and wait_variable() methods. Using these two methods, parts of the code can be simplified.

For example, in the program, a dialog box pops up, wait for the user to enter and press OK, and then continue the operation. Such a program must use the wait_ series of methods, and continue the program according to the content bound to wait after the user completes the input, otherwise the user's input content cannot be directly manipulated.

At this point we can use the wait_ series of methods:

  • Tk/Toplevel.wait_window(window=None): Indicates that the content to be executed later will be blocked and executed after the subsequent window components are destroyed.
  • Tk/Toplevel.wait_visibility(window=None): means to block the following content, and wait for the visibility of the window to change before executing the following content.
  • Tk/Toplevel.wait_variable(name="PY_VAR"): Indicates blocking the following content until name (a PY_VAR, such as String Var, Int Var)

In this way, the if statement can be used directly to make the code concise.

from tkinter import *

root = Tk()
root.wait_window(root)
print("root已经被销毁")

#mainloop()
#mainloop不需要执行,因为这一段执行到时root已经被销毁

In the above code, the content after wait_window will not be executed, but when the user clicks the close button of the window to destroy the window, the following "root has been destroyed" will be printed.

from tkinter import *

root = Tk()
var = StringVar()
Button(root, text="改变var", command=lambda:var.set("change")).pack()
root.wait_variable(var)
print("var的内容出现了改变")

mainloop()

 In this piece of code, only when the content of var changes, the blocking will stop and the following print function will be executed. When the user clicks the Button, the content of var is set to "change", wait_variable detects the content change, runs the following code and prints the content. Since this is not an event, the code that follows will only run once.

from tkinter import *

root = Tk()
label = Label(root, text="")
Button(root, text="改变label的可见性", command=label.pack).pack()
root.wait_visibility(label)
print("label的可见性被改变!")

mainloop()

In this piece of code, when the Button is pressed, the visibility of the label is changed (such as hidden, placed), wait_visibility stops, and the following print code is executed.

When using the wait series of methods, the code will automatically enter the main loop, and you don't need to consider whether the mainloop is written in the front or the back.

Let's look at an example that demonstrates the use of wait_variable.

from tkinter import *

root = Tk()
root.title("判断")
result = Variable(value=None)

Label(root, text="请问1+1=2是否正确?").pack()

Button(root, text="正确", command=lambda: result.set(True)).pack()
Button(root, text="错误", command=lambda: result.set(False)).pack()

root.wait_variable(result) #阻塞下面的进程,直到root.result改变
root.destroy() #在没有选择之前,这一段会一直阻塞

if result.get():
    print("你答对了")
else:
    print("你答错了")

6. Flexible use of the window update method to replace the mainloop to avoid the use of multi-threading or window after method

In tkinter, the most common method is to execute the mainloop at the end of the program, which can be used to refresh the window repeatedly. If you want to perform some operations while refreshing the window, but don't want to use troublesome after or multithreading, you can directly use the while True loop instead.

mainloop() is actually a while True loop, the following two pieces of code are equivalent:

from tkinter import *

#1
root = Tk()
root.mainloop() 

#2
root = Tk()
while True:
    root.update()

For example, if I want to continuously print the user's input in Entry, I can use mainloop, as follows:

from tkinter import *

root = Tk()
entry = Entry(root)
entry.pack()

def print_entry():
    print(entry.get())
    root.after(0, print_entry)

root.after(0, print_entry)
mainloop()

But if you use while True: root.update() , you can write it like this:

from tkinter import *

root = Tk()
entry = Entry(root)
entry.pack()

def print_entry():
    print(entry.get())

while True:
    root.update()
    print_entry()

 This is not only much simpler, but also the logic is very clear, and there is no need to consider complicated issues such as canceling after.

7. Disable windows

root = Tk()
root.attributes("-disable", True)

When set to True, the window will be disabled, and cannot be activated, dragged, or operated on. Set to False to cancel disabling.

8. Make the component in the busy state

tk can keep a window or component in a "busy" state. Components in the busy state cannot do anything, and display a loading style (watch) while the mouse is over it.

tkinter does not currently support setting the busy status of components through methods, and can only call Tcl commands.

from tkinter import *

root = Tk()
b = Button(root, text="BUTTON")
b.pack()

root.tk.call("tk", "busy", "hold", b) #设置为忙碌状态

mainloop()

 

Components in the busy state do not change colors, fonts, etc.

If you want to cancel the busy status, you can use the following command:

root.tk.call("tk", "busy", "forget", widget)

You can also set the mouse style in the busy state, namely:

root.tk.call("tk", "busy", "configure", widget, "-cursor", cursorname)

For more information, please refer to the Tcl/Tk documentation.

9. Invoke the font selection dialog

Tk8.6 adds a new font selection dialog box for font selection. Tkinter has no way to achieve font selection, only by calling Tcl commands.

To display the font selection dialog box, you can use the following command:

root.tk.call("tk", "fontchooser", "show")

However, this method does not return the result of font selection, so it needs to be set before displaying it. A callback function can be passed to handle the font selection result. This callback function must be registered as a Tcl function to realize the function.

def font_changed(font):
    print("选择字体的结果:", font)

root.tk.call("tk", "fontchooser", "configure", "-font", "helvetica 24", "-command", root.register(font_changed))

10. Window theme

Themes are a collection of styles that define the appearance of application components. Different themes have different styles for components.

To apply a window theme to a component, you need to use a ttk component. You need to define ttk.Style() first.

s = ttk.Style()

The theme_names() method returns all built-in themes and themes that are still available on the system.

s.theme_names()

The theme_use method returns the currently used theme. You can also set the theme of the current window with the theme_use method.

 

The picture shows the built-in theme and effect.

Most of the relevant content found above comes from the source code research of tkinter (Tcl/Tk), and many content can also be found in the tkinter source code.

Guess you like

Origin blog.csdn.net/qq_48979387/article/details/119695934