当前位置: 首页 > 知识库问答 >
问题:

Tkinter和GUI大小问题

穆仲卿
2023-03-14

有人知道如何保持窗户的大小吗?如你所见,每当我选择一个文件,文件路径将改变GUI大小:

我不确定你是否能看到GUI的图像,但是路径字符串只会使窗口变宽。

我将把下面的代码留给你。我遇到问题的框架是“file_Frame=tk.LabelFrame(root,text=“Open file”,padx=6,pady=6,bg=“Gainsboro”)”之一

# initalize the tkinter GUI
root = tk.Tk()

root.configure(bg='Gainsboro')
root.resizable(0, 0) # makes the root window fixed in size.

root.title("Metadata Population")

#########################################################################
##################### Add ExxonMobil Logo to the title ##################
#########################################################################

root.iconbitmap(r"C:\Users\SCDBOHU\Desktop\GitRepos\SeismicDataAutomation\Project\GUI\EM_Logo.ico")

#########################################################################
##################### Make the console textbox ##########################
#########################################################################

tk.text = Text(root)
scroll = ttk.Scrollbar(root)
scroll.config (command=tk.text.yview)
tk.text.config(yscrollcommand=scroll.set)
tk.text.pack(side = RIGHT, fill = Y)
        

tk.text.insert(tk.END, "Python Version : " + sys.version)  # write text to textbox
tk.text.see(END)


#########################################################################
##################### Add title label ###################################
#########################################################################

Label(root, text="Metadata Automation", bg="Gainsboro", font = "Verdana 16").pack(pady=15, padx=6, side=TOP)


#########################################################################
##################### Create frames #####################################
#########################################################################

file_frame = tk.LabelFrame(root, text="Open File", padx=6, pady=6, bg="Gainsboro")
file_frame.pack(expand = False, fill="both")

checkboxes_frame = tk.LabelFrame(root, text="Population options", padx=6, pady=6, bg="Gainsboro")
checkboxes_frame.pack(expand = True, fill="both")


#########################################################################
############### Add buttons and checkboxes to the frames ################
#########################################################################

# The file/file path text
label_file = tk.Label(file_frame, text="No File Selected", bg="Gainsboro", font = "Verdana 8")
label_file.pack(padx=5, pady=20)

# Add the "BROWSE A FILE" button
button1 = tk.Button(file_frame, text="Browse A File", bg="Gainsboro", font = "Verdana 8", command=lambda: File_dialog())
button1.pack(padx=5, pady=20)

Print1 = tk.Label(file_frame, text="*The program only accepts .xls and .xlsx", bg="Gainsboro", font = "Verdana 7")
Print1.pack(padx=0, pady=20)



#Make checkboxes
survey = tk.IntVar()
project = tk.IntVar()


SurveyCheckbox = Checkbutton(checkboxes_frame, text="Insert a survey", bg="Gainsboro", font = "Verdana 10", variable=survey, onvalue=1, offvalue=3)
ProjectCheckbox = Checkbutton(checkboxes_frame, text="Insert a project", bg="Gainsboro", font = "Verdana 10", variable=project, onvalue=2, offvalue=4)
SurveyCheckbox.pack(padx=5, pady=20)
ProjectCheckbox.pack(padx=5, pady=20)
Print2 = tk.Label(checkboxes_frame, text="*Select what you would like to insert", bg="Gainsboro", font = "Verdana 7")
Print2.pack(padx=0, pady=20)

SurveyCheckbox.deselect()
ProjectCheckbox.deselect()


#Add submit button
Button(root, text="Submit", width= 10, height=3, bg="LightSlateGray", fg="WHITE", font = "Verdana 10", command=lambda: Gui()).pack(padx=0, pady=20)

#########################################################################
##################### Create and load the files #########################
#########################################################################

def File_dialog():
    #This Function will open the file explorer and assign the chosen file path to label_file
    filename = filedialog.askopenfilename(initialdir="/",
                                          title="Select A File",
                                          filetype=(("xlsx files", "*.xlsx"),("All Files", "*.*")))
    filesplit = filename.split("/")[-1]
    
    label_file["text"] = filename
    
    return filename
  
def Load_excel_data():

    #If the file selected is valid this will load the file into the Treeview
    file_path = label_file["text"]
    
    try:

        file = r"{}".format(file_path)
        
        if file[-4:] == ".csv":
            df = pd.read_excel(file, skiprows=3, engine='xlrd')

        else:
            df = pd.read_excel(file, skiprows=3, engine='openpyxl')
        
    except ValueError:
        
        tk.messagebox.showerror("Information", "The file you have chosen is invalid")
        return None

    except FileNotFoundError:
        
        tk.messagebox.showerror("Information", f"No such file as {file_path}")
        return None
    
    return df

#########################################################################
########## Create a function to close de GUI window #####################
#########################################################################
def on_closing():
    if messagebox.askokcancel("Exit", "Do you want to exit?"):
        root.destroy()

#########################################################################
##################### Create the GUI logic ##############################
#########################################################################

def Gui():

    tk.text.tag_configure('success', foreground='green')
    tk.text.tag_configure('information', foreground='blue')
    tk.text.tag_configure('error', foreground='red')
    
    survey_chk = survey.get()
    project_chk = project.get()
    
    df = Load_excel_data()

    connection = utils.CreateConnection()

    try:

        if survey_chk == 1 and project_chk != 2:
            utils.CreateSurvey(connection, df)
            
        
        elif project_chk == 2 and survey_chk != 1:
            utils.CreateProject(connection, df)
        
        elif survey_chk == 1 and project_chk == 2:
            utils.CreateSurvey(connection, df)
            utils.CreateProject(connection, df)
    
    except Exception as e:
        tk.text.insert(tk.END, "Something went wrong:", 'error')
        tk.text.insert(tk.END, e, 'error')
        tk.text.see(END)
    
    else:
        tk.text.insert(tk.END, "\n The upload was successful. You can close the window now\n", 'success')
        tk.text.see(END)

        



#########################################################################
##################### Create the console printer logic ##################
#########################################################################

class PrintLogger(): # create file like object

    def __init__(self, textbox): # pass reference to text widget
        tk.textbox = textbox # keep ref

    def write(self, text):

        try:
            if (text[0] == "#") :
                tk.textbox.insert(tk.END, text[1:], ('important'))  # write text to textbox
                tk.textbox.tag_configure ('important', foreground = 'blue')

            else :
                tk.textbox.insert(tk.END, text)  # write text to textbox

            tk.textbox.see(END)
            tk.textbox.update_idletasks()
            sys.stdout.flush()

        except IndexError:
            tk.textbox.insert(tk.END, text)
        except Exception as e :
            #self.master.destroy()
            sys.exit()

#########################################################################
#################### Code to start the Metadata Populator ###############
#########################################################################

if __name__ == "__main__":
    #create a protocol when closing the window
    root.protocol("WM_DELETE_WINDOW", on_closing)
    root.mainloop()
    utils.ConnectionInit()

共有1个答案

谷泳
2023-03-14

试试这个-

file_frame = tk.LabelFrame(root,width=a,height=b ,text="Open File", padx=6, pady=6, bg="Gainsboro")
file_frame.pack_propagate(False)
file_frame.pack(expand = False, fill="both")

其中a,b是框架的尺寸(您应该计算它以匹配它)和。pack_propagate(False)阻止labelFrame更改其大小

实际上,您不需要宽度高度,只需不指定它即可将其设置为默认大小

 类似资料:
  • 我是python和tkinter的新手。。。我使用Tkinter显示仪表并通过串行com接收信息。我已经准备好GUI,现在需要读取序列值。 我面临的问题是我不能连续读取串行COM。我遇到了,但它仍然不起作用。基本上它不会在控制台上显示任何值。知道可能出了什么问题吗? 这是主要代码。我还有一个文件meter.py

  • 我正在尝试使用一种被广泛接受的方法(暗示该方法是无缝的)制作一个GUI来解决工程设计问题。 此方法的代码在独立运行时需要0.537909984588623秒(不是在tkinter中,而是在普通代码中),并且不会太复杂或混乱。当我尝试使用tkinter修改此代码以适应GUI时,在输入所有输入并选择一个按钮后,即使程序一直在后台运行,它也会变得无响应。 另外,当我强制关闭GUI窗口时,jupyter内

  • 我有一个Tkinter GUI,它显示Matplotlib绘图(Python 2.7.3和Matplotlib 1.2.0rc2),并允许用户配置绘图的某些方面。绘图趋向于变大,因此图形被包装在滚动画布中。配置绘图的一个方面是更改其大小。 现在,虽然绘图一方面可以正常滚动,另一方面也可以调整大小,但这两个操作不能结合使用。下面是演示效果的脚本。(对不起,长度太长了,我不能再短了。)你可以在绘图中滚

  • 问题内容: 我如何将放大和缩小添加到以下脚本,我想将其绑定到鼠标滚轮。如果您正在Linux上测试此脚本,请不要忘记将MouseWheel事件更改为Button-4和Button-5。 问题答案: 据我所知,内置的Tkinter Canvas类缩放不会自动缩放图像。如果无法使用自定义窗口小部件,则可以缩放原始图像,并在调用缩放功能时将其替换在画布上。 下面的代码片段可以合并到您的原始类中。它执行以下

  • 我有一个简单的TKinter GUI,它有一个文本输入框和一个按钮。我想输入文本,点击按钮,让我的程序打印文本。GUI工作正常,除了单击文本输入框并键入时,在调整窗口大小或单击按钮之前,我看不到光标或文本。单击按钮时,文本将显示在输入框中并返回。当我输入文本时,GUI没有更新。我正在OSX10.10上运行Python 3.4。任何想法都欢迎。 下面是代码:

  • 问题内容: 我正在尝试使用该函数查找窗口的大小,但最终返回的结果 我也曾尝试过,但我不断 码 问题答案: 您试图在渲染窗口之前获取尺寸。 在s之前添加一个,它会显示正确的尺寸。