是否可以将if语句与Tkinter按钮一起使用

2024-04-20 03:40:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望发生的是,当我按下另一个按钮时,第一个标签被销毁,只有相应的标签出现在GUI上。有没有一种方法可以将If语句合并到这个过程中,或者我应该用另一种方法来处理它?在

from tkinter import *

root = Tk()
root.geometry("250x50")
def func1():
    label = Label(root, text = 'Hello', fg="White", bg="Orange" )
    label.pack(fill=BOTH, expand=True)
def func2():
    label = Label(root, text = 'Goodbye', fg="White", bg="Orange" )
    label.pack(fill=BOTH, expand=True)

button1 = Button(root, text = "Button 1", command = func1, fg="White", 
bg="Black", width=10, height=5)
button1.pack(side=LEFT)
button2 = Button(root, text = "Button 2", command = func2, fg="White", 
bg="Black", width=10, height=5)
button2.pack(side=LEFT)
root.mainloop()

Tags: 方法textdefbuttonroot标签filllabel
1条回答
网友
1楼 · 发布于 2024-04-20 03:40:19

这是@jasonsharper提出的方法:在开始时创建一个标签,然后使用两个按钮设置其文本和其他属性,确实更容易。在

import tkinter as tk


if __name__ == '__main__':
    root = tk.Tk()
    root.geometry("250x50")

    def set_label(txt):
        label['text'] = txt
        label['fg'] = "White"
        label['bg'] = "Orange"

    button1 = tk.Button(root, text = "Button 1", command = lambda x='hello': set_label(x), fg="White", bg="Black", width=10, height=5)
    button1.pack(side=tk.LEFT)

    button2 = tk.Button(root, text = "Button 2", command = lambda x='bye': set_label(x), fg="White", bg="Black", width=10, height=5)
    button2.pack(side=tk.LEFT)

    label = tk.Label(root, text='')
    label.pack(fill=tk.BOTH, expand=True)

    root.mainloop()

注:

请避免import *>;要保持命名空间的干净,请使用import tkinter as tk

相关问题 更多 >