gpt4 book ai didi

Python Tkinter : How to get status message about menu action?

转载 作者:行者123 更新时间:2023-12-01 05:45:05 24 4
gpt4 key购买 nike

以下内容生成一个 Tkinter 文本字段,其中包含菜单命令的示例(将文本加载到文本字段中)。应该有一个标签充当状态行,显示刚刚执行的命令。因此,当单击“加载”时,我希望显示“文件已加载”。我正在努力获取 self.status进入appmenu 。原因:app必须首先调用(因为 self.text ),但为了拥有 self.statusapp , appmenu应该首先被调用。不?请帮忙。感谢期待。

import Tkinter
import tkFileDialog

class App (object):
def __init__(self, master, status):
self.status = status
frame = Tkinter.Frame(master)
frame.pack(fill="both", expand=1)
self.text_field(frame)
self.status_line(frame)

def status_line (self, frame):
statusline = Tkinter.Label(frame, text = self.status)
statusline.pack()

def text_field(self, frame):
self.text = Tkinter.Text(frame)
self.text.pack(fill="both", expand=1)

class App_Menu(object):
def __init__(self, master, text, status):
self.text = text
self.master = master
menubar = Tkinter.Menu(master)
self.menuBar = Tkinter.Menu(master)
master.config(menu=self.menuBar)
self.fillMenuBar(text)

def fillMenuBar(self, text):
self.menuFile = Tkinter.Menu(self.menuBar, tearoff=False)
self.menuFile.add_command(label="Open",command=self.load)
self.menuBar.add_cascade(label="File",menu=self.menuFile)

def load(self):
self.file=tkFileDialog.askopenfile()
self.text.delete(1.0, Tkinter.END)
if self.file:
self.text.insert(1.0,self.file.read())
self.status = "file loaded"

root = Tkinter.Tk()
status = "status"
app = App(root, status)
appmenu = App_Menu(root, app.text, status)
root.mainloop()

最佳答案

使用self.status = ...,您可以为实例变量分配一个新值,但它不会更改标签的文本。为此,您可以使用 StringVar 和 set 方法来更改其值:

class App (object):
# ...
def status_line (self, frame):
statusline = Tkinter.Label(frame, textvariable = self.status)
statusline.pack()
# ...

class App_Menu(object):
def __init__(self, master, text, status):
# ...
self.status = status

# ...
def load(self):
self.file=tkFileDialog.askopenfile()
self.text.delete(1.0, Tkinter.END)
if self.file:
self.text.insert(1.0,self.file.read())
self.status.set("file loaded")

root = Tkinter.Tk()
status = Tkinter.StringVar(root)
status.set("status")

关于Python Tkinter : How to get status message about menu action?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16365707/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com