目标是将变量string1从传递class Display
给另一个Tkinter窗口。因此,当单击名为[在加载功能中]的下一步按钮时class Display
,它将打开一个新的Tkinter窗口。在新窗口中,需要检索来自变量string1的信息class Display
以采取进一步的措施。我可以知道应该创建另一个类Display2吗,还是应该在类Display中添加一个方法?
目前,字符串变量可以作为引用从传递class Display
给class Action_Data
。但是,当单击下一步按钮时,如何将其传递到另一个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的值
错误
使用该lambda
函数传递按钮的command
,这样您就可以传递所需的字符串作为参数。
您无需创建的两个实例Tk
,如果需要另一个窗口,请创建一个Toplevel
。
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, string):
#self.master.destroy() # close the current window
new_window = tk.Toplevel() # create toplevel
var_string2 = Label(new_window, text=string)
var_string2.pack()
new_window.focus()
print (var_string2.cget("text"))
def load(self):
#get value
string1='value1'
self.display.action1(string1)
self.acition_button = tk.Button(self, text="Next",
command= lambda : self.new_window(string1))
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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句