求解python tkinter
# 为什么把函数放在外面就会报错啊!# 报错的代码:
import tkinter as tk
def user_input():
var = e.get()
t.insert('end', var)
def mytk():
window = tk.Tk()
window.title('my window')
e = tk.Entry(window, show=None)
e.pack()
button = tk.Button(window, text='点击', width=15, height=2, command=user_input)
button.pack()
t = tk.Text(window, height=2)
t.pack()
window.mainloop()
mytk()
# 正常运行的代码:
import tkinter as tk
def mytk():
window = tk.Tk()
window.title('my window')
e = tk.Entry(window, show=None)
e.pack()
def user_input():
var = e.get()
t.insert('end', var)
button = tk.Button(window, text='点击', width=15, height=2, command=user_input)
button.pack()
t = tk.Text(window, height=2)
t.pack()
window.mainloop()
mytk()
# 求解!!! 作用域不一样
要不就将其封装成一个类 或者把e当成全局变量
def user_input():
var = e.get()
t.insert('end', var)
def mytk():
global e# 声明全局变量
window = tk.Tk()
window.title('my window')
e = tk.Entry(window, show=None)
e.pack()
button = tk.Button(window, text='点击', width=15,
height=2, command=user_input)
button.pack()
t = tk.Text(window, height=2)
t.pack()
window.mainloop()
mytk()
大马强 发表于 2022-1-25 17:53
作用域不一样
要不就将其封装成一个类
多谢
页:
[1]