我是一名初学者程序员,正在尝试解决一个非常小的问题。 我想制作一个具有2个按钮的GUI,即“打印”和“清除”。 我已经尽力了,但是还不能解决。想要帮助...。 这是我的代码(忽略整洁):
from tkinter import *
main = Tk()
main.geometry("200x200")
global buttonstate
def change():
buttonstate = True
return buttonstate
button1 = Button(main, text="Button", command=change)
if buttonstate==True:
global label
label = Label(main, text= "this works")
elif buttonstate==False:
pass
button2 = Button(main, text="clear", command=lambda: label.pack_forget())
button1.pack()
button2.pack()
label.pack()
main.mainloop()
我无法循环执行所有操作,也无法在单击按钮时打印语句... 谢谢。
答案 0 :(得分:1)
这是带有两个按钮和一个标签的GUI,
from tkinter import *
main = Tk()
# label where you will print text
text_label = Label(main, width=20)
text_label.grid(row=0, columnspan=2, padx=8, pady=4)
# function to print text in label
def print_text():
# the message you want to display
your_text = "Some message.."
# update the text of your label with your message
text_label.config(text=your_text)
# function to clear text in label
def clear_text():
# clear the label text by passing an empty string
text_label.config(text='')
# print button
# command option is the function that you want to call when the button is pressed
print_btn = Button(main, text='Print', command=print_text, width=8)
print_btn.grid(row=1, column=0, padx=8, pady=4)
# clear button
clear_btn = Button(main, text='Clear', command=clear_text, width=8)
clear_btn.grid(row=1, column=1, padx=8, pady=4)
main.mainloop()
输出GUI
点击
点击
Clear
按钮以清除消息
我已注释了代码的每个部分。希望您能理解