我有两个python文件,FirstWindowFile
和SecondWindowFile
。
我在第一个按钮中创建了一个按钮,按下后,我想创建一个按钮
第二个文件中有一个按钮的新窗口。
按下第二个文件中的按钮后,我需要更改
1中全局变量的值
FirstWindowFile
代码:
import tkinter as tk
from tkinter import*
import SecondWindowFile
root = Tk() # create a main window
root.geometry("750x250")
global myglobal # this is the global i want to change
myglobal = 0
btn1 = tk.Frame(root, borderwidth=5, relief="ridge")
btn1.grid(column=0, row=0)
# when I press this button I send the SecondWindowFile to ChangeValue()
Analyze = tk.Button(btn1, text="Analyze",
command=lambda: SecondWindowFile.ChangeValue()).grid(row=0, column=0)
# myglobal has to take new value (sent from SecondWindowFile) so to
# be used for new calculations
print(myglobal)
root.mainloop()
SecondWindowFile
代码:
import tkinter as tk
from tkinter import*
def changeMyNum():
gl=1
# I need this value of gl to be returned to the FirstWindowFile and be the
# new value of global myglobal
def ChangeValue():
secondWindow = Tk() # create a 2nd window
secondWindow.geometry("150x150")
btn2 = tk.Frame(secondWindow, borderwidth=5, relief="ridge") # create a button
btn2.grid(column=0, row=0)
# by pressing the button goes to changeMyNum()
ChangeVal = tk.Button(secondWindow, text="Press to Change Global",
command=lambda: changeMyNum).grid(row=0, column=0)
我认为你的问题有一个更一般的答案:
从
SecondWindowFile
开始,定义一个函数,该函数创建一个GUI,该GUI在按下按钮时结束并返回一个变量在
FirstWindowFile
中,将变量定义为SecondWindowFile
函数的返回值例如:
getValue()
是您创建的返回var的函数如果您需要进一步澄清,请询问
我的答案与@furas非常相似,但说明了如何定义和使用} 中,并显式地将该作为参数传递给另一个模块的文件中定义的函数
class
来避免(或至少最小化)使用全局变量——这对您想要做的事情都不起作用。在这种情况下,将其存储在tkinter ^{正如他(和我)强烈建议的那样,我也在很大程度上尝试遵循PEP 8 - Style Guide for Python Code,特别是关于naming conventions部分中的内容(这也适用于模块文件名称)
first_window.py
second_window.py
您无法从一个文件访问另一个文件中的全局文件。这不是个好主意。您应该以显式的方式使用变量-如果您要使用
list
、dict
或tk.IntVar
、tk.StringVar
来保留值,那么您可以将其作为参数发送,函数可以更改list
、dict
或tk.IntVar
、tk.StringVar
中的值,并且可以在其他函数中更改该值tk.IntVar
也很有用,因为您可以将其分配给label,当您更改IntVar
时,它会自动更新Label
中的值您只需记住
IntVar
需要.get()
和.set()
才能使用值main.py
第二个窗口.py
现在您可以将其分配到
Label
以显示当前值完整代码:
main.py
第二个窗口.py
PEP 8 Style Guide for Python Code
PEP 20 Python Zen
相关问题 更多 >
编程相关推荐