【发布时间】:2021-09-23 11:29:28
【问题描述】:
有谁知道如何保持窗口的大小?如您所见,每当我选择一个文件时,文件路径都会改变 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()
【问题讨论】:
标签: python user-interface tkinter