我正在尝试使用tkinter模块在GUI上工作。我使用随机问候语生成器创建了标签。但是,它们与先前生成的标签重叠。这是代码:
import tkinter
import random
window = tkinter.Tk()
# to rename the title of the window
window.title("GUI")
window.geometry("500x500")
#defining Functions
def search_greetings():
phrases = ["Hallo ", "Hoi ", "Greetings "]
name = str(entry1.get())
text = ".Please enter your search term below."
return phrases[random.randint(0, 2)] + name + text
def search_display():
greeting = search_greetings()
# This creates the text field
greeting_display = tkinter.Label(window,text = search_greetings())
greeting_display.grid(row=6,column=1)
search_box = tkinter.Entry()
search_box.grid(row=7)
# pack is used to show the object in the window
label = tkinter.Label(window, text = "Hello World! Welcome to my app")
label.grid(row = 0)
# creating 2 text labels and input labels
tkinter.Label(window, text = "Username").grid(row = 2) # this is placed in 1 0
# 'Entry' is used to display the input-field
entry1 = tkinter.Entry()
entry1.grid(row = 2, column = 1) # this is placed in 1 1
tkinter.Label(window, text = "Password").grid(row = 3) # this is placed in 2 0
tkinter.Entry().grid(row = 3, column = 1) # this is placed in 2 1
# 'Checkbutton' is used to create the check buttons
tkinter.Checkbutton(window, text = "Keep Me Logged In").grid(columnspan = 2) # 'columnspan' tells to take the width of 2 columns
# you can also use 'rowspan' in the similar manner
# Submit button
button = tkinter.Button(text = "Submit",command = search_display).grid(row = 5)
window.mainloop()
它返回如下标签: 问候1234。请在下面输入搜索词。
G Hallo ashita。请在下面输入搜索词。
G Hallo ashita。请在下面输入搜索词。
请检查代码中的错误。
答案 0 :(得分:1)
似乎您每次都在制作一个新标签。您可以这样编辑标签的文本:
mylabel = tkinter.Label(root, text="First!")
mylabel["text"] = "Second!"
这将显示“第二!” (打包后)。标签打包后,您甚至可以更改文本。