【发布时间】:2021-04-08 03:35:14
【问题描述】:
目标是从class Display 传递变量string1 以在另一个Tkinter 窗口中使用。
因此,当单击名为 Next [in class Display load function] 的按钮时,它将打开一个新的 Tkinter 窗口。在新窗口中,需要检索来自 class Display 的变量 string1 以进行进一步操作。我可以知道我应该创建另一个类 Display2,还是应该在类 Display2 中添加一个方法?
目前,字符串变量可以作为引用从class Display 传递到class Action_Data。但是当点击 Next 按钮时,如何将它传递给另一个 Tkinter 窗口呢?
我正在尝试通过回调函数 new_window 获取变量。只是不确定它是否是这样完成的。任何指针将不胜感激。非常感谢。
from tkinter import *
import tkinter as tk
#Application window
root = tk.Tk()
#Display Class
class Display (tk.Frame):
def __init__(self, master, display_data):
tk.Frame.__init__(self,master)
self.master = master
#passing data as reference
self.display= display_data
#button
self.load_button = tk.Button(self, text="Load", command=self.load)
self.load_button.pack()
def new_window(self):
self.master = tk.Tk() # create another Tk instance
var_string2 = Label(self, text="<<string1 value>>")
var_string2.pack()
print (var_string2)
def load(self):
#get value
string1='value1'
self.display.action1(string1)
self.acition_button = tk.Button(self, text="Next",
command=self.new_window)
self.acition_button.pack()
#Action_Data Class
class Action_Data(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self,master)
def action1(self, path1):
var_path1 = path1
print(var_path1)
display= Action_Data(root)
display.pack()
reader = Display(root, display)
reader.pack()
pathlabel2 = Label(root)
root.mainloop()
Issue
现在新窗口是空白的,无法从加载函数中检索变量 string1 的值
错误
【问题讨论】:
-
请尝试将此代码合并为一个minimal reproducible example。
-
@BryanOakley 代码更新,请看一下,非常感谢
-
为什么要销毁窗口并创建另一个?为什么不直接删除当前窗口中的项目并放入新项目?这样你就可以保留你想要保留的东西,比如 StringVar。
-
@JacksonPro 代码已编辑,预期输出是新窗口能够从加载方法中获取变量 string1 的值
-
@Novel,内容替换是一个很好的建议,您能否说明如何做到这一点,非常感谢
标签: python python-3.x tkinter