在main.py
文件的function1
函数中,我想导入textbox1
和textbox2
来自 page1.py
文件的 Page1(tk.Frame)
类。
我收到错误 NameError: name 'textbox1' is not Defined
,因为 textbox1
和 textbox2
未正确导入。这是我正在使用的代码。我究竟做错了什么?怎么解决?
main.py
import tkinter as tk
from tkinter import ttk
from tkinter import *
from page1 import Page1
root = tk.Tk()
root.geometry('480x320')
style = ttk.Style()
style.theme_use('default')
style.configure('TNotebook', tabposition='wn', background='white', tabmargins=0)
style.configure('TNotebook.Tab', background='white', width=10, focuscolor='yellow', borderwidth=0)
style.map('TNotebook.Tab', background=[('selected', 'yellow')])
nb = ttk.Notebook(root)
nb.place(x=0, y=70)
page1 = Page1(nb, width=492, height=905)
nb.add(page1, text='Tab 1', compound='left')
def function1(textbox1, textbox2):
val_1 = "example 1"
textbox1.insert(0, val_1)
val_2 = "example 1"
textbox2.insert(0, val_2)
button1 = Button(root, text="Button", command= function1(textbox1, textbox2))
button1.place(x=0, y=0)
root.mainloop()
page1.py
import tkinter as tk
from tkinter import ttk
from tkinter import *
from tkinter import ttk
import tkinter as tk
import tkinter.font as tkFont
from tkinter import ttk
class Page1(tk.Frame):
def __init__(self, master, **kw):
super().__init__(master, **kw)
self.textbox1 = ttk.Entry(self, width=7)
self.textbox1.place(x=10, y=10)
self.textbox2 = ttk.Entry(self, width=7)
self.textbox2.place(x=10, y=40)
最佳答案
据我所知,要访问 main.py
中 function1 函数中的 textbox1 和 textbox2
,您应该使用 self.textbox1 将它们设为实例变量
和 self.textbox2
。
import tkinter as tk
from tkinter import ttk
class Page1(tk.Frame):
def __init__(self, master, **kw):
super().__init__(master, **kw)
self.textbox1 = ttk.Entry(self, width=7)
self.textbox1.place(x=10, y=10)
self.textbox2 = ttk.Entry(self, width=7)
self.textbox2.place(x=10, y=40)
并且 main.py
应该是这样的
import tkinter as tk
from tkinter import ttk
from tkinter import *
from page1 import Page1
def function1():
val_1 = "example 1"
page1.textbox1.delete(0, tk.END) # Clear any existing text
page1.textbox1.insert(0, val_1)
val_2 = "example 2"
page1.textbox2.delete(0, tk.END) # Clear any existing text
page1.textbox2.insert(0, val_2)
button1 = Button(root, text="Button", command=function1)
button1.place(x=0, y=0)
root.mainloop()
这应该可以解决问题。您可以尝试一下,希望这会有所帮助。
注意:如果您只想编辑脚本。
您可以为按钮添加此行,其中使用 page1
对象
button1 = Button(root, text="Button", command= function1(page1.textbox1, page1.textbox2))
我已经测试过了,它对我来说效果很好:
关于python - 将小部件从另一个文件中的类导入到函数中。名称错误 : name 'textbox1' is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77208733/