我目前正在努力使用从另一个类(使用tkinter)派生的输入来改变另一个类中的输出。这是我的代码:
#there are many of these defs, this is just one i used as an example
def command_ssumowrestler(self):
self.master.withdraw()
toplevel = tk.Toplevel(self.master)
toplevel.geometry("30x70")
app=ClassConfirmation(toplevel)
global cs_hobby
cs_hobby = 'sumo_wrestler'
class ClassConfirmation:
def __init__ (self, master):
self.master = master
self.frame = tk.Frame(self.master)
confirmclass_label = tk.Label(master, width = 20, fg = 'blue',text= "Do You Wish to Proceed as:")
confirmclass_label.pack()
#here i use the variable defined and set globally in the previously block, which always leaves me with an error saying cs_hobby is not defined
classdescription_label = tk.Label(master, width =50, text='test ' + cs_hobby + ' hello')
classdescription_label.pack()
self.confirmclassButton = tk.Button(self.frame, text = 'Confirm', width = 20, command = self.close_windows)
self.confirmclassButton.pack()
self.frame.pack()
def close_windows (self):
self.master.withdraw()
app=dragonrealmP1
#this just opens a different class
答案 0 :(得分:1)
global
不会创建变量 - 它只会通知函数/方法使用全局变量而不是局部变量。首先,您必须在类之前创建此变量。
顺便说一句:如果你使用课程,那你为什么不在头等课程中使用
self.cs_hobby = 'sumo_wrestler'
并在ClassConfirmation
sone_object_name.cs_hobby
或
app = ClassConfirmation(toplevel, 'sumo_wrestler')
class ClassConfirmation:
def __init__ (self, master, cs_hobby):
# here use cs_hobby
修改强>
首先:global cs_hobby
不创建全局变量。它仅通知函数使用全局cs_hobby
而不是本地cs_hobby
使用您需要的global
cs_hobby = "" # create global variable (outside classes)
def command_ssumowrestler(self):
global cs_hobby # inform function to use global variable
# rest
cs_hobby = 'sumo_wrestler' # set value in global variable
app = ClassConfirmation(toplevel)
class ClassConfirmation:
def __init__ (self, master):
global cs_hobby # inform function to use global variable
# rest
print(cs_hobby) # get value from global variable
cs_hobby = 'tenis' # set value in global variable
在没有全局变量的情况下工作
def command_ssumowrestler(self):
self.cs_hobby = 'sumo_wrestler' # create local variable
app = ClassConfirmation(toplevel, self.cs_hobby) # send local value to another class
self.cs_hobby = app.cs_hobby # receive value from another class
class ClassConfirmation:
def __init__ (self, master, hobby):
self.cs_hobby = hobby # create local variable and assign value
# rest
print(self.cs_hobby) # use local value
self.cs_hobby = 'tenis' # use local value