我正在创建一个函数,在其中我将文本文件的内容输出到Tkinter中的“Message”小部件。用户选择对应于文本文件的选项,然后按“确定”。
我遇到的问题是,在选择两个连续选项后,我不知道如何清除消息框。
问题: 在输出第二个文本之前,如何清除第一个文本的消息框?目前,第二个文本输出在第一个文本的顶部。
我尝试过Message.delete和Message.clear,但我认为它们不适用于消息小部件。
任何帮助都将不胜感激。
这是我的代码:
def learn(event):
''' This function creates a new window within the main window, passes an event(left mouse click), and creates a text heading'''
root = Toplevel(window)
menu_choice = StringVar(root)
menu_choice.set("Select") # initial value
selection_message = Message(root, text = "Choose which area of finances you'd like to learn about below!", width = 180)
selection_message.grid(row = 0, column = 0, columnspan = 6)
menu_options = OptionMenu(root, menu_choice, "Stocks", "Bonds", "Index Funds", "Exchange Traded Funds (ETF's)")
menu_options.grid(row = 1, column = 2)
def selection():
learn_area = menu_choice.get()
learn_file = open('C:\\Users\\nicks_000\\PycharmProjects\\untitled\\SAT\\GUI\\Text Files\\{0}.txt'.format(learn_area))
learn_text = learn_file.read()
learn_file.close()
about_message = Message(root, text = learn_text, width = 300, relief = RAISED)
about_message.grid(row = 3, column = 0, columnspan = 6)
selection_button = Button(root, text="OK", command=selection)
selection_button.grid(row = 2, column = 2)
答案 0 :(得分:1)
您的问题是您在选择功能中创建了about_message
窗口小部件,因此每次调用该函数时都会重新创建一个窗口小部件。我建议你在选择功能之外创建小部件,这样你就可以about_message.configure(text="new text")
。这是代码:
from tkinter import *
window = Tk()
def learn():
''' This function creates a new window within the main window, passes an event(left mouse click), and creates a text heading'''
root = Toplevel(window)
menu_choice = StringVar(root)
menu_choice.set("Select") # initial value
selection_message = Message(root, text = "Choose which area of finances you'd like to learn about below!", width = 180)
selection_message.grid(row = 0, column = 0, columnspan = 6)
menu_options = OptionMenu(root, menu_choice, "Stocks", "Bonds", "Index Funds", "Exchange Traded Funds (ETF's)")
menu_options.grid(row = 1, column = 2)
def selection():
learn_area = menu_choice.get()
learn_file = open('C:\\Users\\nicks_000\\PycharmProjects\\untitled\\SAT\\GUI\\Text Files\\{0}.txt'.format(learn_area))
learn_text = learn_file.read()
learn_file.close()
about_message.configure(text=learn_text)
selection_button = Button(root, text="OK", command=selection)
selection_button.grid(row = 2, column = 2)
# create about_message outside the selection function
# to be able to modify its content
about_message = Message(root, text = "", width = 300, relief = RAISED)
about_message.grid(row = 3, column = 0, columnspan = 6)
Button(window,text="test", command=learn).pack()
window.mainloop()