TKInter 条目与主窗口一起不同步



我正在使用以下代码,我有 2 个问题, 1.当我尝试最大化窗口时,"条目"小部件未与主窗口对齐/最大化,并看到滚动文本和"条目"小部件之间的间隙。 2. 其次,当我尝试打开或每当我的应用程序处于活动状态时,我尝试在条目小部件中设置光标,但由于某种原因它不起作用。知道我犯了什么错误吗?

import tkinter as tk
from tkinter import scrolledtext
class Main:
def __init__(self, master):
self.master = master
master.title("Main")
width = master.winfo_screenwidth()
height = master.winfo_screenheight()
master.minsize(width=1066, height=766)
master.maxsize(width=width, height=height)
self.frame = tk.Frame(self.master)
text_area = scrolledtext.ScrolledText(self.master,width=75,height=35)
text_area.pack(side="top",fill='both',expand=True)
text_entry = tk.Entry(self.master,width=65)
text_entry.pack(side="top",fill=X, expand=True,ipady=3, ipadx=3)
text_entry.configure(foreground="blue",font=('Arial', 10, 'bold', 'italic'))
text_entry.focus()
self.frame.pack()
def initial(self):
print ("initializing")
def main(): 
root = tk.Tk()
app = Main(root)
root.mainloop()
if __name__ == '__main__':
main()

我可以解决您的输入字段无法正确扩展的问题。

这是因为您有fill=X,这不是填充的有效输入。而是使用fill="x".我相信您对输入字段差距较大的第二个问题是因为您设置了expand = True而是将其更改为expand = False

也就是说,我更喜欢使用grid()几何管理器。看看我下面的例子,了解如何使用网格和权重来做到这一点。

使用grid()管理器时,您可以准确地告诉每个小部件沿网格所需的位置。权重的使用用于告诉行或列它应该随窗口扩展多少(如果有(。这与sticky="nsew"相结合将帮助我们控制窗口内的内容扩展。

import tkinter as tk
from tkinter import scrolledtext

class Main(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.title("Main")
width = self.winfo_screenwidth()
height = self.winfo_screenheight()
self.minsize(width=1066, height=766)
self.maxsize(width=width, height=height)
self.rowconfigure(0, weight=1)
self.rowconfigure(1, weight=0)
self.columnconfigure(0, weight=1)
text_area = scrolledtext.ScrolledText(self,width=75,height=35)
text_area.grid(row=0, column=0, ipady=3, ipadx=3, sticky="nsew")
text_entry = tk.Entry(self,width=65)
text_entry.grid(row=1, column=0, ipady=3, ipadx=3, sticky="ew")
text_entry.configure(foreground="blue",font=('Arial', 10, 'bold', 'italic'))
text_entry.focus()
def initial(self):
print ("initializing")
if __name__ == '__main__':
root = Main()
root.mainloop()

更新:

为了澄清您在填充和扩展方面的问题,我已使用更正更新了您的代码,以便您可以看到它的工作原理。

import tkinter as tk
from tkinter import scrolledtext
class Main:
def __init__(self, master):
self.master = master
master.title("Main")
width = master.winfo_screenwidth()
height = master.winfo_screenheight()
master.minsize(width=1066, height=766)
master.maxsize(width=width, height=height)
self.frame = tk.Frame(self.master)
text_area = scrolledtext.ScrolledText(self.master,width=75,height=35)
text_area.pack(side="top",fill='both',expand=True)
text_entry = tk.Entry(self.master,width=65)
text_entry.pack(side="top",fill="x", expand=False, ipady=3, ipadx=3)
text_entry.configure(foreground="blue",font=('Arial', 10, 'bold', 'italic'))
text_entry.focus()
self.frame.pack()
def initial(self):
print ("initializing")
def main(): 
root = tk.Tk()
app = Main(root)
root.mainloop()
if __name__ == '__main__':
main()

最新更新