如何通过在另一个文件中按tkinter按钮来更改文件中的全局变量?

2024-09-26 18:10:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个python文件,FirstWindowFileSecondWindowFile。 我在第一个按钮中创建了一个按钮,按下后,我想创建一个按钮 第二个文件中有一个按钮的新窗口。 按下第二个文件中的按钮后,我需要更改 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)

Tags: 文件thetoimporttkintercolumnroot按钮
3条回答

我认为你的问题有一个更一般的答案:

SecondWindowFile开始,定义一个函数,该函数创建一个GUI,该GUI在按下按钮时结束并返回一个变量

FirstWindowFile中,将变量定义为SecondWindowFile函数的返回值

例如:

FirstWindowFile:
global myVar
def onButtonPress():
    return SecondWindowFile.getValue()
myVar = onButtonPress()

SecondWindowFile:
def getValue():
   def onButtonPress():
      return 'The Value You Want'

getValue()是您创建的返回var的函数

如果您需要进一步澄清,请询问

我的答案与@furas非常相似,但说明了如何定义和使用class来避免(或至少最小化)使用全局变量——这对您想要做的事情都不起作用。在这种情况下,将其存储在tkinter ^{}中,并显式地将该作为参数传递给另一个模块的文件中定义的函数

正如他(和我)强烈建议的那样,我也在很大程度上尝试遵循PEP 8 - Style Guide for Python Code,特别是关于naming conventions部分中的内容(这也适用于模块文件名称)

first_window.py

import tkinter as tk
import second_window as sw


class MyApp:
    def __init__(self,  master):
        self.frame = tk.Frame(master, borderwidth=5, relief="ridge")
        self.frame.grid(row=0, column=0)
        self.my_var = tk.IntVar(master=master, value=0)
        analyze_btn = tk.Button(self.frame, text="Analyze",
                                command=lambda: sw.change_value(self.my_var))
        analyze_btn.grid(row=0, column=0, columnspan=2)
        tk.Label(self.frame, text="My var:").grid(row=1, column=0)
        tk.Label(self.frame, textvariable=self.my_var).grid(row=1, column=1)

if __name__ == '__main__':
    root = tk.Tk()  # Create a main window.
    root.geometry("750x250")
    my_app = MyApp(root)
    root.mainloop()

second_window.py

import tkinter as tk


def change_my_num(var):
    var.set(var.get() + 1)  # Increment value in IntVar.


def change_value(var):
    second_window = tk.Tk()  # Create a 2nd window.
    second_window.geometry("150x150")

    frame2 = tk.Frame(second_window, borderwidth=5, relief="ridge")
    frame2.grid(row=0, column=0)

    change_val_btn = tk.Button(frame2, text="Press to Change Global",
                               command=lambda: change_my_num(var))
    change_val_btn.grid(row=0, column=0)

    done_btn = tk.Button(frame2, text="Done", command=second_window.destroy)
    done_btn.grid(row=1, column=0)

您无法从一个文件访问另一个文件中的全局文件。这不是个好主意。您应该以显式的方式使用变量-如果您要使用listdicttk.IntVartk.StringVar来保留值,那么您可以将其作为参数发送,函数可以更改listdicttk.IntVartk.StringVar中的值,并且可以在其他函数中更改该值

tk.IntVar也很有用,因为您可以将其分配给label,当您更改IntVar时,它会自动更新Label中的值

您只需记住IntVar需要.get().set()才能使用值

main.py

myglobal = tk.IntVar(value=0)  # you have to create after `root`


Button(..., command=lambda:second_window.change_value(myglobal)

第二个窗口.py

def change_value(variable):
    
    Button(..., command=lambda:change_my_num(variable))


def change_my_num(variable):  

    variable.set( variable.get()+1 )
    
    print(variable.get())

现在您可以将其分配到Label以显示当前值

Label(..., textvariable=myglobal)

完整代码:

main.py

import tkinter as tk
#from tkinter import *  # PEP8: `import *` is not prefered
import second_window

# 
root = tk.Tk()  # create a main window
root.geometry("750x250")

myglobal = tk.IntVar(value=0)  # you have to create after `root`

btn1 = tk.Frame(root)
btn1.grid(column=0, row=0)

# PEP8: `lower_case_names` for variables
analyze = tk.Button(btn1, text="Analyze", command=lambda:second_window.change_value(myglobal))
analyze.grid(row=0, column=0)

l = tk.Label(btn1, textvariable=myglobal)
l.grid(row=1, column=0)

print(myglobal.get())  # it runs it before `mainloop` starts GUI and shows window - so it is useless.

root.mainloop()

print(myglobal.get())  # it runs it after closing window

第二个窗口.py

import tkinter as tk  # PEP8: `import *` is not preferred

def change_my_num(variable):  # PEP8: `lower_case_names` for functions

    variable.set( variable.get()+1 )
    
    print(variable.get())
    

def change_value(variable):
    second_window = tk.Toplevel()  # use `Toplevel to create a 2nd window
    
    b = tk.Button(second_window, text="Press to Change Global", command=lambda:change_my_num(variable))
    b.grid(row=0, column=0)

PEP 8 Style Guide for Python Code


PEP 20 Python Zen

... Explicit is better than implicit. ...

相关问题 更多 >

    热门问题