我试图遵循面向对象的方法创建一个简单的tkinter应用程序来显示一些数据,但我很难在 Select 文件的菜单栏类和最终处理文件的主应用程序类之间传递值.现在,我只是想在屏幕上的标签中显示文件名.我试图将文件名作为tk传递.StringVar,但屏幕上没有更新.下面是简化代码.

import tkinter as tk
from tkinter import filedialog as fd #needed for file dialogues
from tkinter import ttk

class MenuBar(tk.Menu):
  def __init__(self):
    super().__init__()
    self.file_audio = tk.StringVar()

    fileMenu = tk.Menu(self, tearoff=0)
    fileMenu.add_command(label="Select file...", command=self.select_file)
    self.add_cascade(label="File", menu=fileMenu)

  # method to select a single file
  def select_file(self):
    self.file_audio = fd.askopenfilename(title='Open a file')
    
class App(tk.Tk):
  def __init__(self):
    super().__init__()

    self.title('Title')
    self.geometry("800x300")
    
    self.menubar = MenuBar()
    self.config(menu=self.menubar)

    self.createWidgets()

  def createWidgets(self):
    self.file_info = ttk.Label(self, text = self.menubar.file_audio)
    self.file_info.grid(column=1, row=1)

def main():
  app = App()
  app.mainloop()
    
if __name__ == "__main__":
  main()

推荐答案

代码中有两个问题:

  1. textvariable option should be used instead of text option in ttk.Label(...)
  def createWidgets(self):
    self.file_info = ttk.Label(self, textvariable = self.menubar.file_audio)
    self.file_info.grid(column=1, row=1)
  1. 使用self.file_audio.set(...)代替MenuBar.select_file()中的赋值
  def select_file(self):
    self.file_audio.set(fd.askopenfilename(title='Open a file'))

Python相关问答推荐

如何计算部分聚合数据的统计数据

仅对matplotlib的条标签中的一个条标签应用不同的格式

无法使用equals_html从网址获取全文

比较两个二元组列表,NP.isin

Select 用a和i标签包裹的复选框?

根据条件将新值添加到下面的行或下面新创建的行中

ModuleNotFound错误:没有名为flags.State的模块; flags不是包

使用setuptools pyproject.toml和自定义目录树构建PyPi包

Python中绕y轴曲线的旋转

梯度下降:简化要素集的运行时间比原始要素集长

我想一列Panadas的Rashrame,这是一个URL,我保存为CSV,可以直接点击

如何在Python中找到线性依赖mod 2

Tkinter菜单自发添加额外项目

在单次扫描中创建列表

python sklearn ValueError:使用序列设置数组元素

Polars map_使用多处理对UDF进行批处理

如何在Python 3.9.6和MacOS Sonoma 14.3.1下安装Pyregion

mdates定位器在图表中显示不存在的时间间隔

如何反转一个框架中列的值?

需要帮助使用Python中的Google的People API更新联系人的多个字段'