小邓学编程 发表于 2020-11-26 13:34:34

我这是用了一个假的global吗?

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Administrator.WIN7U-20190717R\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
File "C:\Users\Administrator.WIN7U-20190717R\Desktop\编程\安装包制作工具\Alpha 0.1\Main.py", line 35, in 添加
    w7.insert(w5.get(),END)
NameError: name 'w7' is not defined

import zipfile
import os
from tkinter import *

ver = "Alpha 0.1"
main = Tk()
main.title("安装包制作工具 "+ver)

def start():
global w1
global w2
global w3
global main
w1.grid_forget()
w2.grid_forget()
w3.grid_forget()

name = w1.get()

try:
    os.mkdir(name)
except:
    pass

w5 = Entry(main)
w5.grid(row = 0,column = 0)

w7 = Listbox(main)
w7.grid(row = 1,column = 0)

def 添加():
    global w5
    global w7
   
    w7.insert(w5.get(),END)

w6 = Button(main,text = "添加",command = 添加)
w8 = Label(main,text = "请在\n输入\n框中\n输入\n目标\n绝对\n路径")

w6.grid(row = 0,column = 1)
w8.grid(row = 1,column = 1)

w1 = Entry(main)
w2 = Label(main,text = "请输入项目名称:")
w3 = Button(main,text = "开始",command = start)

w1.grid(row = 0,column = 1)
w2.grid(row = 0,column = 0)
w3.grid(row = 0,column = 2)

main.mainloop()

Twilight6 发表于 2020-11-26 13:47:54


你 w7 和 w5 本身定义时候就是局部变量

所以不能通过 global 来声明,你应该先在全局设置两个值,例如:

w5,w7 = None,None

然后在 start 函数进行声明(这里只拷贝部分代码):

def start():
    global w1
    global w2
    global w3
    global w5
    global w7
    global main

内部函数添加可以改成这样:

def 添加():
    w7.insert(w5.get(), END)

Ps:建议不要用中文设置为变量名
页: [1]
查看完整版本: 我这是用了一个假的global吗?