我正在尝试创建一个收集实验数据的程序。我已经成功创建了一个包含标签和条目小部件的表。但是,当尝试通过收集输入的数据使入口小部件起作用时,我的脚本将失败。
import tkinter as tk
from PIL import ImageTk, Image
class Window(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.master.title("Data Analyser")
tk.Label(self.master, text="Cell Number").grid(row=1, sticky=tk.W)
tk.Label(self.master, text="1").grid(row=2)
tk.Label(self.master, text="1").grid(row=2)
tk.Label(self.master, text="Treatment").grid(row=1, column=2)
Treatment_1 = tk.Entry(self.master).grid(row=2,column=2)
Treatment_2 = tk.Entry(self.master).grid(row=3,column=2)
tk.Button(self.master, text = "Submit", command = self.getInput).grid(row = 14, column = 2)
def getInput(self):
global Treatment_Data
a = Treatment_1.get()
b = Treatment_2.get()
Treatment_Data = [a,b]
root = tk.Tk()
root.geometry("500x450")
app = Window(root)
root.mainloop()
我希望上面的代码将生成一个名为“ Treatment_Data”的全局变量,但是不幸的是,当我单击“提交”小部件时,收到以下错误消息:
Traceback (most recent call last):
File "C:\Users\xxxx\lib\tkinter\__init__.py", line 1550, in __call__
return self.func(*args)
File "<ipython-input-134-2b5d212a0dcf>", line 47, in getInput
a = self.Treatment_1.get()
AttributeError: 'NoneType' object has no attribute 'get'
任何澄清将不胜感激。
答案 0 :(得分:0)
仅需要使用self来将Treatment_1和Treatment_2设置为类变量,然后才能在回调函数getInput()中访问它们。
注释中提到的另一件事是,您需要将这两个部分分开-
1.创建一个Entry Widget,然后
2.将其放置在网格中。
您应该创建一个Entry小部件并将其存储在Treatment_1中。完成后,您应该使用Treatment_1变量将小部件放置在网格中的所需位置。
import tkinter as tk
from PIL import ImageTk, Image
class Window(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.master.title("Data Analyser")
tk.Label(self.master, text="Cell Number").grid(row=1, sticky=tk.W)
tk.Label(self.master, text="1").grid(row=2)
tk.Label(self.master, text="1").grid(row=2)
tk.Label(self.master, text="Treatment").grid(row=1, column=2)
self.Treatment_1 = tk.Entry(self.master)
self.Treatment_2 = tk.Entry(self.master)
self.Treatment_1.grid(row=2,column=2)
self.Treatment_2.grid(row=3,column=2)
tk.Button(self.master, text = "Submit", command = self.getInput).grid(row = 14, column = 2)
def getInput(self):
global Treatment_Data
a = self.Treatment_1.get()
b = self.Treatment_2.get()
Treatment_Data = [a,b]
print(Treatment_Data)
root = tk.Tk()
root.geometry("500x450")
app = Window(root)
root.mainloop()