从函数更新 tkinter 中的文本小部件

时间:2021-03-11 17:34:56

标签: python function tkinter widget

问题:

我正在尝试从包含一些文本的函数中更新相同的文本小部件框。而是每次都会出现一个全新的文本窗口。

这是我的代码:

from tkinter import *
import os

#Tkinter graphics

homepage = Tk()
homepage.title("My first GUI")
# set size of window
homepage.geometry('1200x400')
# Add image file 
bg = PhotoImage(file = "maxresdefault.png") 
    
# Show image using label 
label1 = Label( homepage, image = bg) 
label1.place(x = 0, y = 0) 

label2 = Label( homepage, text = "Test App") 
label2.pack() 

# Create Frame 
frame1 = Frame(homepage) 
frame1.pack()

#button initatiors
def buttonupdate():
    S = Scrollbar(homepage)
    T = Text(homepage, height=100, width=30)
    T.pack()
    T.pack(side=RIGHT, fill= Y)
    S.pack(side = RIGHT, fill = Y)
    S.config(command=T.yview)
    T.insert(END, "test")
    T.config(yscrollcommand=S.set, state=DISABLED)


    

# Static buttons
tickets30button = Button(text = "This is button 1", command=buttonupdate) 
tickets30button.place(x=0, y=26) 

mcibutton = Button(text = "This is button 2") 
mcibutton.place(x=0, y=52)

hdebutton = Button(text = "This is button 3")
hdebutton.place(x=0, y=78)

homepage.mainloop()

如果我点击第一个按钮三次,结果如下:

如果您有任何我可以尝试的建议,请告诉我。

感谢您的时间,

1 个答案:

答案 0 :(得分:1)

感谢@TheLizzard,我能够在每次点击按钮时更新我的​​文本窗口,而不是创建一个新窗口。

他提到将创建文本窗口的代码部分移到函数之外,而将创建文本的代码部分保留在函数内部。

之前:

#button initiators
def buttonupdate():
    S = Scrollbar(homepage)
    T = Text(homepage, height=100, width=30)
    T.pack()
    T.pack(side=RIGHT, fill= Y)
    S.pack(side = RIGHT, fill = Y)
    S.config(command=T.yview)
    T.insert(END, "test")
    T.config(yscrollcommand=S.set, state=DISABLED)

之后:(更新)

S = Scrollbar(homepage)
T = Text(homepage, height=100, width=30)
T.pack(side=RIGHT, fill= Y)
S.pack(side = RIGHT, fill = Y)
S.config(command=T.yview)
T.config(yscrollcommand=S.set, state=DISABLED)

#button initatiors
def myTicketstatusbutton():
    T.delete(1.0,END)
    T.insert(END, "test")
    
相关问题