首页 > 解决方案 > 使用 tkinter 模块重叠状态

问题描述

我正在尝试使用 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 你好 ashita。请在下面输入您的搜索词。

G 你好 ashita。请在下面输入您的搜索词..v。

请检查代码中的错误。

标签: pythonpython-3.xtkinter

解决方案


似乎您每次都在制作新标签。您可以像这样编辑标签的文本:

mylabel = tkinter.Label(root, text="First!")
mylabel["text"] = "Second!"

这将显示“第二个!” (打包后)。您甚至可以在打包标签后更改文本。


推荐阅读