首页 > 解决方案 > Python Tkinter 在其前面显示带有 Hi 的名称

问题描述

from tkinter import *
from tkinter.ttk import *

def process_name():
    """Do something with the name (in this case just print it)"""

    global name_entry
    print("Hi {}".format(name.get()))
    

def main():
    """Set up the GUI and run it"""

    global name_entry
    window = Tk()
    
    name_label = Label(window, text='Enter name a name below:')
    name_label.grid(row=0, column=0)
    name_entry = Entry(window)
    name_entry.grid(row=1, column=3)
    button = Button(window, text='Say hello', command=process_name, padding=10)
    button.grid(row=1, column=0, columnspan=2)
 
    window.mainloop()

        
main()

标签: pythontkinter

解决方案


这应该可以满足您的需求。请务必阅读代码注释以了解我的操作是否正确。

虽然有几点,

  • 不建议使用通配符导入,如from tkinter import *. 原因很简单。两者都tkinter具有tkinter.ttk共同的类和函数,例如Button,Label等等。解释器决定使用哪些变得模棱两可。
  • 使用.config().configure()更新 中的标签、按钮、条目或文本小部件tkinter。就像我在下面的代码中所做的那样。

您的代码已修改

from tkinter import *
from tkinter.ttk import *

def process_name():
    """Do something with the name (in this case just print it)"""

    global name_entry # this will print hi {name} to terminal.
    print("Hi {}".format(name_entry.get()))

    global nameLabel # to change'the label with hi{name} text below the button.
    nameLabel.configure(text=f'Hi {name_entry.get()}')

    
    

def main():
    """Set up the GUI and run it"""

    global name_entry, nameLabel
    window = Tk()
    
    name_label = Label(window, text='Enter name a name below:')
    name_label.grid(row=0, column=0)
    name_entry = Entry(window)
    name_entry.grid(row=1, column=3)
    button = Button(window, text='Say hello', command=process_name, padding=10)
    button.grid(row=1, column=0, columnspan=2)

    # I defined a label BELOW the button to show how to change
    nameLabel = Label(window, text=' ') # an empty text Label
    nameLabel.grid(row=2)
 
    window.mainloop()

        
main()

推荐阅读