我正在写我的第一个程序,我不知道如何解决这个问题。我一周前就开始学习Python了,对Tkinter和OOP还是很陌生的。我让这个脚本(D&D NPC Generator)在没有使用OOP的情况下工作,但是我想看看如何使用OOP来实现它,因为大多数人似乎都喜欢使用Tkinter。在
以下是输入窗口的代码:
class Input:
def __init__(self, master):
ideals = ["Good", "Evil",
"Lawful", "Chaotic",
"Neutral", "Other"]
ideal_selection = StringVar()
ideal_selection.set(ideals[0])
self.name_label = Label(master, text="NPC Name: ")
self.name_entry = Entry(master)
self.ideal_label = Label(master, text="Ideal Type: ")
self.ideal_entry = OptionMenu(master, ideal_selection, *ideals)
self.submit_button = Button(text="Submit", command=self.close_window)
self.name_label.grid(row=0, column=0)
self.name_entry.grid(row=0, column=1)
self.ideal_label.grid(row=1, column=0)
self.submit_button.grid(columnspan=2, row=3, column=0)
self.ideal_entry.grid(row=1, column=1)
def close_window(self):
global name
global ideal_type
name = self.name_entry.get()
ideal_type = self.ideal_selection.get()
self.master.destroy()
它又回来了:
^{pr2}$我不知道出什么事了。我使用这个GUI窗口的目的是让用户输入NPC的名称,然后从drown菜单中选择一个选项,以确定用户希望NPC拥有什么样的理想。对我做错的地方进行纠正和解释会很有帮助的,谢谢。在
您已将
ideal_selection
声明为局部变量,而不是类实例变量。 因此,调用self.ideal_selection.get()
将失败,因为没有要引用的self
。在您需要将声明从:
ideal_selection = StringVar()
更改为:this.ideal_selection = StringVar()
,并将所有其他引用更改为this.ideal_selection
。在请注意,您已经为其他所有内容(
self.name_entry
)执行了此操作。。。在后记:
我不鼓励你在这里使用
global
。当您在OOP原则下运行tkinter时,您可以将类中的值返回给调用脚本。在(请注意,最后我建议不要使用
from tkinter import *
)。在看看如果您的代码修改为:
相关问题 更多 >
编程相关推荐