Python Tkinter(保存输入项)
所以我想做一个可以保存入口点的代码,我已经做了,但是出现了一个问题 这是我的代码:Python Tkinter(保存输入项),python,tkinter,Python,Tkinter,所以我想做一个可以保存入口点的代码,我已经做了,但是出现了一个问题 这是我的代码: import tkinter as tk def players(): global p1, p2 p1 = plyr1.get() p2 = plyr2.get() #USERNAMES if (p1 != "") or (p2 != "") or (p1 != p2): print("Player 1
import tkinter as tk
def players():
global p1, p2
p1 = plyr1.get()
p2 = plyr2.get()
#USERNAMES
if (p1 != "") or (p2 != "") or (p1 != p2):
print("Player 1 = " + p1)
print("Player 2 = " + p2)
if (p1 == "") or (p2 == ""):
frame1.tkraise()
messagebox.showerror("INVALID USRNAME", "PLEASE FILL THE ENTRY POINT !")
elif p1 == p2:
print(p1 + " (Player 1's username)"+ " and " + p2 + " (Player 2's username)"+ " ARE SAME")
frame1.tkraise()
messagebox.showerror("INVALID USERNAME", "PLEASE USE DIFFERENT USERNAME !")
else :
frame2.tkraise()
root = tk.Tk()
.
.
.
tk.Label(frame3, text = "Player 2 = ", font = _font).grid(row = 2, column = 0, sticky = 'W')
**p2_data = tk.Label(frame3, text = p2, font = _font )**
p2_data.grid(row = 2, column = 1, sticky = 'E')
所以,在这条粗体线上,它表示p2没有定义。您知道为什么以及如何修复它吗?问题是您没有正确返回变量。在函数中,您将变量设置为全局变量。通常的做法是限制全局变量的使用,而是将变量从函数返回到代码,即
返回您的_变量
,并获取返回的变量并将其存储在代码的其余部分,编写您的_变量=您的_函数()
函数中的变量是局部变量。它们需要返回到主代码
例如:
def your_function():
widget_input = entry_widget.get()
# returns your variable to the rest of the code
return widget_input
# stores the output of the function in a variable
your_var = your_function()
由于您有两个变量,因此需要同时返回并保存这两个变量:
def your_function():
input1 = widget1.get()
input2 = widget2.get()
return input1, input2
va1, var2 = your_function()
我假设您在调用players()
之前设置了标签,因此尚未定义p2
。只需将p2=“”
放在标签上方的某个位置。我已经将p2=“”放在播放器上方()我已经调用了函数,但我没有显示它。在使用变量p2
之前是否调用了函数?是否定义了plyr2
?在函数中定义后,尝试打印p2
,查看是否返回任何内容。这意味着您没有正确返回变量。在函数中,您将变量设置为全局变量。通常的做法是限制全局变量的使用,而是将函数中的变量返回到代码中,即返回您的\u变量
,并获取返回的变量并将其存储在代码的其余部分,编写您的\u变量=您的\u函数()
我不懂,您能写出示例吗?