如何在复选框中更改变量状态并在另一个函数中使用它

huangapple go评论68阅读模式
英文:

How to change a variable status in check button and use it in another function

问题

这是您提供的代码的翻译部分:

我在主窗口中有一个复选按钮当单击复选按钮时我需要使用两个函数第一个函数打开一个弹出窗口第二个函数将activate_SPI变量从inactive更改为active”。我希望在单击GUI中的compute按钮以打印ok使用activate_SPI状态但是我遇到了以下错误

 **NameError: name 'activate_SPI' is not defined**

如何修复这个错误

```python
import pandas as pd
import numpy as np
from standard_precip import spi
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from tkinter.messagebox import showinfo
import os
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from tkinter import * 
from PIL import Image, ImageTk

class EGEDT(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.create_widgets()
        # 主窗口的尺寸
        master.geometry("300x300")

    def create_widgets(self):
        self.top_frame = ttk.Frame(self)

        padding_x = 8
        padding_y = 7
        self.working_dir = "/"

        # 创建一个复选按钮
        self.ab_frame = ttk.Frame(self.top_frame)
        self.ab_label = ttk.Label(self.ab_frame, text="选择复选按钮:")
        self.ab_label.grid(row=1, column=0, padx= 5, pady= 5)

        var1 = tk.IntVar()

        self.a = ttk.Checkbutton(self.ab_frame, text="SPI", variable=var1, onvalue=1, offvalue=0, command=lambda: [f() for f in [self.open_popup_SPI, self.func_activate_SPI]])
        self.a.grid(row=2, column=1, padx= 0, pady= 0)
        self.ab_frame.grid(row=2, column=0, sticky=tk.W, padx=padding_x, pady=padding_y)
        self.top_frame.grid(row=0, column=0)

        # 输出文件小部件
        self.out_frame = ttk.Frame(self.top_frame)
        self.out_label = ttk.Label(self.out_frame, text="保存文件:")
        self.out_label.grid(row=0, column=0, sticky=tk.W)
        self.out_string = tk.StringVar()
        self.out_entry = ttk.Entry(self.out_frame, width=7, textvariable=self.out_string)
        self.out_entry.grid(row=1, column=0)
        self.out_btn = ttk.Button(self.out_frame, width=7, text="...", command=self.out_file_selector)
        self.out_btn.grid(row=1, column=1)
        self.out_frame.grid(row=5, column=0, sticky=tk.W, padx=padding_x, pady=padding_y)

        # 创建“ok”按钮以将SPI文件保存到硬盘
        self.buttons = ttk.Frame(self.out_frame)
        self.PDF = ttk.Button(self.out_frame, text="计算", width=10, command=self.Compute_TI_model_and_Extract_EG)
        self.PDF.grid(row=1, column=2)
        self.buttons.grid(row=5, column=0, sticky=tk.E, padx=padding_x, pady=padding_y)

        self.buttons = ttk.Frame(self.out_frame)
        self.cancel = ttk.Button(self.buttons, text="取消", width=7, command=self.master.destroy)
        self.cancel.grid(row=2, column=2)
        self.buttons.grid(row=2, column=2, sticky=tk.E, padx=padding_x, pady=padding_y)

    def open_popup_SPI(self):
       top= Toplevel(self.top_frame)
       top.geometry("750x250")
       top.title("子窗口")
       Label(top, text= "你好,世界!", font=('Mistral 18 bold')).place(x=150,y=80)

    activate_SPI = "inactive"

    def func_activate_SPI(self):
        nonlocal activate_SPI
        activate_SPI = "active"

    def Geotiff_file_selector(self):
        result = self.Geotiff_string.get()
        result = filedialog.askopenfilename(initialdir = self.working_dir, title = "选择文件", filetypes = (("Geotiff 文件","*.tif"),("所有文件","*.*")))
        self.Geotiff_string.set(result)
        self.working_dir = os.path.dirname(result)

    def out_file_selector(self):
        result = self.out_string.get()
        result = filedialog.asksaveasfilename(initialdir = self.working_dir, title = "保存文件", filetypes = (("Geotiff 文件","*.tif"),("所有文件","*.*")))
        self.out_string.set(result)
        self.working_dir = os.path.dirname(result)

    def Compute_TI_model_and_Extract_EG(self):
        if activate_SPI == 'active':
            print('ok')

def main():
    root = tk.Tk()   
    root.title("主窗口")
    app = EGEDT(master=root)
    app.mainloop()

main()
英文:

I have a check button located in a main window. I need to use two functions when the check button is clicked. The first function opens a pop up and the second function changes the "activate_SPI" variable from "inactive" to "active". I want to use the "activate_SPI" status in another function that is called when I press the "compute" button in GUI to print "ok". However, I face the following error:

"NameError: name 'activate_SPI' is not defined"

How can I fix this error?

import pandas as pd
import numpy as np
from standard_precip import spi
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from tkinter.messagebox import showinfo
import os
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, 
NavigationToolbar2Tk)
from tkinter import * 
from PIL import Image, ImageTk
class EGEDT(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
# dimensions of the main window
master.geometry("300x300")
def create_widgets(self):
self.top_frame = ttk.Frame(self)
padding_x = 8
padding_y = 7
self.working_dir = "/"
# Create a check button   
self.ab_frame = ttk.Frame(self.top_frame)
self.ab_label = ttk.Label(self.ab_frame, text="Select the check button:")
self.ab_label.grid(row=1, column=0, padx= 5, pady= 5)
var1 = tk.IntVar()
self.a = ttk.Checkbutton(self.ab_frame,text="SPI",variable=var1, onvalue=1, offvalue=0,command=lambda: [f() for f in [self.open_popup_SPI, self.func_activate_SPI]])
self.a.grid(row=2, column=1, padx= 0, pady= 0)
self.ab_frame.grid(row=2, column=0, sticky=tk.W, padx=padding_x, pady=padding_y)       
self.top_frame.grid(row=0, column=0)
# Output file widget
self.out_frame = ttk.Frame(self.top_frame)
self.out_label = ttk.Label(self.out_frame, text="Save : ")
self.out_label.grid(row=0, column=0, sticky=tk.W)
self.out_string = tk.StringVar()
self.out_entry = ttk.Entry(self.out_frame, width=7, textvariable=self.out_string)
self.out_entry.grid(row=1, column=0)
self.out_btn = ttk.Button(self.out_frame, width=7, text="...", command=self.out_file_selector)
self.out_btn.grid(row=1, column=1)
self.out_frame.grid(row=5, column=0, sticky=tk.W, padx=padding_x, pady=padding_y)
# Create ok button to save the SPI excek file into the hard drive
self.buttons = ttk.Frame(self.out_frame)
self.PDF = ttk.Button(self.out_frame, text="Compute", width=10, command=self.Compute_TI_model_and_Extract_EG)
self.PDF.grid(row=1, column=2)
self.buttons.grid(row=5, column=0, sticky=tk.E, padx=padding_x, pady=padding_y)
self.buttons = ttk.Frame(self.out_frame)
self.cancel = ttk.Button(self.buttons, text="Cancel", width=7, command=self.master.destroy)
self.cancel.grid(row=2, column=2)
self.buttons.grid(row=2, column=2, sticky=tk.E, padx=padding_x, pady=padding_y)
def open_popup_SPI(self):
top= Toplevel(self.top_frame)
top.geometry("750x250")
top.title("Child Window")
Label(top, text= "Hello World!", font=('Mistral 18 bold')).place(x=150,y=80)
activate_SPI = "inactive"
def func_activate_SPI(activate_SPI):
# global activate_SPI  
activate_SPI = "active"
def Geotiff_file_selector(self):
result = self.Geotiff_string.get()
result = filedialog.askopenfilename(initialdir = self.working_dir, title = "Select File", filetypes = (("Geotiff files","*.tif"),("all files","*.*")))
self.Geotiff_string.set(result)
self.working_dir = os.path.dirname(result)
def out_file_selector(self):
result = self.out_string.get()
result = filedialog.asksaveasfilename(initialdir = self.working_dir, title = "Save File", filetypes = (("Geotiff files","*.tif"),("all files","*.*")))
self.out_string.set(result)
self.working_dir = os.path.dirname(result)
def Compute_TI_model_and_Extract_EG(self):
if activate_SPI == 'active':
print('ok')
def main():
root = tk.Tk()   
root.title("Main window")
app = EGEDT(master=root)
app.mainloop()
main()

答案1

得分: 0

Here is the translated content:

由于activate_SPI是一个类变量,它可以通过EGEDT.activate_SPI来访问。

然而,我建议使用一个实例变量来替代局部变量var1

class EGEDT(tk.Frame):
    ...
    def create_widgets(self):
        ...
        self.activate_SPI = tk.IntVar()  # 替代 var1

        self.a = ttk.Checkbutton(self.ab_frame, text="SPI", variable=self.activate_SPI, 
                                 onvalue=1, offvalue=0, command=self.open_popup_SPI)
        ...

    ...
    #activate_SPI = "inactive"   # 不要使用类变量

    # 这个函数完全不必要
    def func_activate_SPI(self):
        pass

    ...
    def Compute_TI_model_and_Extract_EG(self):
        if self.activate_SPI.get():
            print("ok")
英文:

Since activate_SPI is a class variable, it is accessed by using EGEDT.activate_SPI.

However I would suggest to use an instance variable which replaces the local variable var1 instead:

class EGEDT(tk.Frame):
    ...
    def create_widgets(self):
        ...
        self.activate_SPI = tk.IntVar()  # replace var1

        self.a = ttk.Checkbutton(self.ab_frame, text="SPI", variable=self.activate_SPI, 
                                 onvalue=1, offvalue=0, command=self.open_popup_SPI)
        ...

    ...
    #activate_SPI = "inactive"   # don't use class variable

    # this function is not necessary at all
    def func_activate_SPI(self):
        pass

    ...
    def Compute_TI_model_and_Extract_EG(self):
        if self.activate_SPI.get():
            print("ok")

huangapple
  • 本文由 发表于 2023年5月18日 09:06:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76277120.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定