我试图用tkinter建立AI,但我有一个问题。我已经完成了测试,但看起来input_get变量似乎没有变化。当我在函数中调用变量时它可以工作但如果我在外面调用它就不会。你有什么建议吗? (它只是代码的一部分,框架,输入字段(Entry)等已经放好了)
from tkinter import *
from tkinter import font
ia_answers = ""
input_get = ""
window = Tk()
window.config(cursor="wait")
input_frame = LabelFrame(window, text="User :", borderwidth=4)
input_frame.pack(fill=BOTH, side=BOTTOM)
input_user = StringVar()
input_field = Entry(input_frame, text=input_user)
input_field.pack(fill=BOTH, side=BOTTOM)
ia_frame = LabelFrame(window, text="Discussion",borderwidth = 15, height = 200, width = 200)
ia_frame.pack(fill=BOTH, side=TOP, expand = True)
printopt = font.Font(family = "Times")
text = Text(ia_frame, state='disabled', bg ="grey")
text.pack(fill = BOTH, expand = True, side = "left")
text.tag_configure("right", justify="right", font=printopt)
text.tag_configure("left", justify="left", font=printopt)
scr = Scrollbar(ia_frame)
scr.config(command=text.yview)
text.config(yscrollcommand=scr.set)
scr.pack(side="right", fill="y", expand=False)
def Enter_pressed(event):
"""Took the current string in the Entry field."""
global input_get
input_get = input_field.get()
input_user.set("")
text.configure(state='normal')
text.insert("end", "\n"+input_get+"\n", "left")
text.insert("end", "\n"+ia_answers+"\n", "right")
text.configure(state='disabled')
text.yview(END)
return input_get
def inputget(event):
if input_get == "ok":
ia_answers = "test"
input_field.bind("<Return>", Enter_pressed, inputget)
window.mainloop()
谢谢。 伊兰·罗斯勒
答案 0 :(得分:0)
两个问题:
首先,当您第一次运行程序时,if input_get == "ok"
正在执行一次。如果您希望它在特定时间运行,请将其置于事件驱动函数中。
其次,在input_get
函数中分配了Enter_pressed
。当该函数结束时,其所有局部变量都超出范围并被丢弃 - 包括input_get
。由于您无法return
Button
小部件或按键,因此如果您想在不同的功能或其他范围内使用它,您必须将其保存为。您可以通过在函数运行之前初始化变量来完成此操作(例如input_get = ''
,然后在函数中声明global input_get
。这将向解释器指示您打算为此全局变量赋值。如果没有此声明,您可以读取全局变量的值,但重新分配给它们只会分配给您不想要的同名的新本地引用。但是,更好的选择是转到面向对象的方法并将其保存为实例变量self.input_get
(请参阅here和here)。