尝试使用Tkinter将复选框指定给操作时,“未定义变量”

2024-10-02 20:42:57 发布

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

我是Python或编程新手。 我正在尝试将tkinter复选框绑定到命令,但遇到问题

我已经创建了一个应用程序,可以根据用户输入将数据保存到xlsx文件中。当用户选择相关选项时,它们应该被“激活”,但是当我点击相关复选框时,我会得到一个错误(现在将命令分配给一个复选框只是为了检查它是否有效)

下面是我的全部代码,下面是我添加的错误代码。我还添加了GIU窗口,这样您就可以看到它的外观以及我的确切意思

我发现有一两个线程在讨论这个问题,但我认为问题的根源并不相同。我正在将Python 3.9与Anaconda和Spyder一起使用

有关守则: .

  from tkinter import *
import tkinter as tk
from tkinter import filedialog
from termcolor import cprint ,colored
import pydicom
import pandas as pd




class gettingDataFromDICOM:
    def DICOMData(dcmread):
        pass
    #Asking the user to choose input location
    print('Welcome to DTETool v1.1')
    

def filelocainput():
    global Data
    filelocationinput = filedialog.askopenfilename()
    Data = pydicom.dcmread(filelocationinput , force = True )
    



    print('PatientID -',Data.PatientID)
    
    
    df = pd.DataFrame ({'PatientID ': [Data.PatientID]})

class tkgui:
    pass

def activate():
  if   Data.PatientID.get() == 1:
            scale.config(state=ACTIVE)
  elif Data.PatientID.get() == 0:
            scale.config(state=DISABLED)
     


Checkboxes =Tk()
Checkboxes.geometry('400x320')
TitleSelDCM = Label(Checkboxes , text ='DICOM fields selection',fg='white')
TitleSelDCM.place(y=0 ,x=120)
CheckboxWindowbg = PhotoImage(file="C:\Tools\DTETool\SeconderyBG.png")
CheckboxWindowbg_label = Label(Checkboxes , image=CheckboxWindowbg)
CheckboxWindowbg_label.place(y=0,x=0 , relwidth =1 , relheight=1)


CheckBoxPID = IntVar()
CheckBoxPID = Checkbutton(Checkboxes , text = 'PatientID', bg = '#0B5ED8' ,fg = 'white', onvalue = 1 , offvalue = 0  , variable = CheckBoxPID ,command =activate)
CheckBoxPID.place(y=20 , x=20)
Checkboxes.mainloop()

错误:

  Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Program Files\Spyder\pkgs\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:\Tools\DTETool\DTEToolv1.1\DTEtool.py", line 113, in activate
    if   Data.PatientID.get() == 1:
NameError: name 'Data' is not defined

An image with the relevant parts

谢谢大家!


Tags: infromimportdatagettkinterdefplace
1条回答
网友
1楼 · 发布于 2024-10-02 20:42:57

编辑:问题是您没有在局部范围内声明变量Data,而只是在函数范围内。还请注意,您正在初始化函数filelocainput中的Data,但从未调用它

根据注释中的TheLizzard答案,在函数filelocainput中添加一个global Data语句作为第一个语句。然后在使用Data之前,找到一个合适的位置来调用函数filelocainput()

编辑:下面是一个使用global的小示例:


def foo():
    global x
    x = 1

foo()
print(x)

在代码中,它应该类似于以下内容(跳过不相关的部分):

from tkinter import *
import tkinter as tk
from tkinter import filedialog
from termcolor import cprint ,colored
import pydicom
import pandas as pd

...

def filelocainput():
    global Data
    ....


filelocainput()
...

作为一个简单的关闭循环的解决方案,这应该可以让它发挥作用。然而,这不是唯一的方法,当然也不是最佳实践

相关问题 更多 >