How can I resize the treeView in Tkinter Python
The table might be here
enter image description here
I'm getting this
enter image description here
Here's the code
from tkinter import *
from tkinter import ttk
white = "#FFFFFF"
window = Tk()
window.geometry("640x415")
listframe=Frame(
window,
bg=white
)
listframe.grid(
row=1,
column=1,
sticky='NSEW'
)
listFields = ['First name','Last name', 'Number', 'Email']
tree = ttk.Treeview(listframe,columns=listFields)
tree.grid(row=1, column=0, columnspan=2, sticky="nsew") # columnspan=2 goes here.
scroll = ttk.Scrollbar(listframe)
scroll.grid(row=1, column=2, sticky="nse") # set this to column=2 so it sits in the correct spot.
scroll.configure(command=tree.yview)
tree.configure(yscrollcommand=scroll.set)
listframe.columnconfigure(1, weight=1)
listframe.rowconfigure(1, weight=1)
window.resizable(False, False)
window.mainloop()
I can't resize the TreeView, it covers the left frame
from tkinter import *
from tkinter import ttk
bgcolor1="#FFB6C1"
bgcolor2="#FFEACC"
grey = "#606060"
chalk = "Chalkduster"
white = "#FFFFFF"
black = "#000000"
window = Tk()
window.geometry("640x415")
window.columnconfigure(0,weight=1)
window.columnconfigure(1,weight=1)
window.rowconfigure(0, weight=1)
window.rowconfigure(1, weight=8)
window.rowconfigure(2, weight=1)
pinkframe=Frame(window,bg=bgcolor1)
pinkframe.grid(
row=0,
column=0,
rowspan=3,
sticky='WENS'
)
searchFrame=Frame(
window,
bg=bgcolor2
)
searchFrame.grid(
row=0,
column=1,
sticky='WENS'
)
listframe=Frame(
window,
bg=white
)
listframe.grid(
row=1,
column=1,
sticky='NSEW'
)
delFrame=Frame(
window,
bg=bgcolor2
)
delFrame.grid(
row=2,
column=1,
sticky='WENS'
)
welcome = Label(
pinkframe,
text="Welcome!",
height=1,
font=(chalk, 30),
fg=black,
bg=bgcolor1
)
welcome.place(x=80,y=5)
addNew = Label(
pinkframe,
text="Add new contact",
height=1,
font=(chalk, 18),
fg=black,
bg=bgcolor1
)
addNew.place(x=70,y=100)
#First name
fName = Label(
pinkframe,
text="First name",
height=1,
font=(chalk, 13),
fg=grey,
bg=bgcolor1
)
fName.place(x=8,y=140)
fEntry = Entry(
pinkframe,
width=20,
justify='left',
relief = "ridge",
highlightthickness=0
)
fEntry.place(x=100,y=140)
#Last name
lName = Label(
pinkframe,
text="Last name",
height=1,
font=(chalk, 13),
fg=grey,
bg=bgcolor1
)
lName.place(x=8,y=180)
lEntry = Entry(
pinkframe,
width=20,
justify='left',
relief = "ridge",
highlightthickness=0
)
lEntry.place(x=100,y=180)
#Phone number
pNum = Label(
pinkframe,
text="Phone",
height=1,
font=(chalk, 13),
fg=grey,
bg=bgcolor1
)
pNum.place(x=8,y=220)
pEntry = Entry(
pinkframe,
width=20,
justify='left',
relief = "ridge",
highlightthickness=0
)
pEntry.place(x=100,y=220)
#email
eMail = Label(
pinkframe,
text="email",
height=1,
font=(chalk, 13),
fg=grey,
bg=bgcolor1
)
eMail.place(x=8,y=260)
eEntry = Entry(
pinkframe,
width=20,
justify='left',
relief = "ridge",
highlightthickness=0
)
eEntry.place(x=100,y=260)
#add
addButton= Button(
pinkframe,
text="ADD",
height=2,
bg = "#FF5FDB",
fg = black,
font=(chalk,16 ))
addButton.place(x=150,y=300)
searchEntry = Entry(
searchFrame,
width=25,
justify='left',
relief = "ridge",
highlightthickness=0
)
searchEntry.place(x=10,y=8)
searchButton= Button(
searchFrame,
text="Search",
height=1,
bg = "#FF5FDB",
fg = black,
font=(chalk,10))
searchButton.place(x=245,y=7)
editButton= Button(
listframe,
text="Edit",
height=1,
bg = "#FF5FDB",
fg = black,
font=(chalk,10))
editButton.place(x=260,y=0)
#contacts list
def showList():
global tree
listFields = ['First name','Last name', 'Number', 'Email']
tree = ttk.Treeview(listframe,columns=listFields)
tree.grid(row=1, column=0, columnspan=2, sticky="nsew") # columnspan=2 goes here.
scroll = ttk.Scrollbar(listframe)
scroll.grid(row=1, column=2, sticky="nse") # set this to column=2 so it sits in the correct spot.
scroll.configure(command=tree.yview)
tree.configure(yscrollcommand=scroll.set)
listframe.columnconfigure(1, weight=1)
listframe.rowconfigure(1, weight=1)
tree.heading(0,text='First name', anchor=NW)
tree.column("#0", anchor=CENTER, stretch=NO, width=80)
tree.heading(1, text='Last name', anchor=NW)
tree.column("#1", anchor=CENTER, stretch=NO, width=80)
tree.heading(2, text='Phone', anchor=NW)
tree.column("#2", anchor=CENTER, stretch=NO, width=80)
tree.heading(3, text='Email', anchor=NW)
tree.column("#3", anchor=CENTER, stretch=NO, width=80)
showList()
window.resizable(False, False)
window.mainloop()
Related
I have a window to display multiple treeview widgets. Currently there are some empty row spaces below the treeview when I expand it and I'm not sure on how to fill the empty spaces below dynamically when I expand the window. I have tried adjusting the rowspan/columnspan options but could not get the desired output as described in image below. I have also included a reproduceable code below for testing my program. Please help to advise on which part I need to make changes. Thanks!
import shutil
import tkinter as tk
import tkinter.ttk as ttk
import tempfile
import zipfile, re, os
from tkinter import *
from tkinter import filedialog
from pathlib import Path
import tkinter.messagebox
from fpdf import FPDF
from datetime import datetime, timedelta
import ctypes
DEPTH = 2
EXCLUDES = {'__MACOSX', 'resources'}
class HomePage(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
self.notebook = ttk.Notebook() # Create a notebook widget
self.add_tab1()
self.notebook.grid(row=0)
self.notebook.pack(expand=1, fill="both")
def add_tab1(self):
tab1 = tab_one(self.notebook)
self.notebook.add(tab1, text="Home")
class data_table(object):
def __init__(self, site, panels_count, tev_count):
self.site = site
self.panels_count = panels_count
self.tev_count = tev_count
class tab_one(Frame):
def __init__(self, *args, **kwargs):
Frame.__init__(self, *args, **kwargs)
# Creating frames on the window/canvas for the first tab
frame_selectfile = tk.LabelFrame(self, text="Step 1: Zip File Extraction ", bd=6) # Frame1 on the window/canvas
frame_selectfile.grid(column=0, row=0, padx=10, pady=10, sticky='NSEW') # Positioning frame1
frame_selectfile.configure(borderwidth=1)
self.grid_columnconfigure(1, weight=1) # Configuring the column for the main window/canvas
self.grid_rowconfigure(1, weight=1) # Configuring the row for the main window/canvas
frame_checkpd = tk.LabelFrame(self, text="Step 2: Check PD ", bd=6) # Frame2 on the window/canvas
frame_checkpd.grid(column=1, row=0, padx=10, pady=10, sticky='NSEW') # Positioning frame2
frame_checkpd.configure(borderwidth=1)
self.grid_columnconfigure(1, weight=1) # Configuring the column for the main window/canvas
self.grid_rowconfigure(1, weight=1) # Configuring the row for the main window/canvas
#Frame to display data in treeview
frame_tree = tk.LabelFrame(self, text="PD Results ", bd=6) # Frame2 on the window/canvas
frame_tree.grid(column=0, row=1, columnspan=2, rowspan=2, padx=10, pady=10, sticky='NSEW') # Positioning frame2
frame_tree.configure(borderwidth=1)
self.grid_columnconfigure(1, weight=1) # Configuring the column for the main window/canvas
self.grid_rowconfigure(1, weight=1) # Configuring the row for the main window/canvas
# Initializing all variables in frame_selectfile
file_ID = tk.StringVar()
location_id = tk.StringVar()
unzip_status = tk.StringVar()
tmpdir = tempfile.TemporaryDirectory().name
f_tem_sdir = open(os.getcwd()+"\\temp_dir.txt", "w")
f_tem_sdir.write(tmpdir)
f_tem_sdir.close()
zip_filename = tk.StringVar()
site_id = tk.StringVar()
site_id.set("0")
data_table_list = []
middleframe = tk.LabelFrame(frame_selectfile, bd=5)
databaseView = ttk.Treeview(middleframe, selectmode="browse")
label_filename = tk.Label(frame_selectfile, text=" ", width=10, relief='flat').grid(column=0, row=1, padx=5,
pady=5, sticky='NW')
label_filelocation = tk.Label(frame_selectfile, text="File Location:", width=12, relief='flat').grid(column=0,
row=2,
padx=5,
pady=5,
sticky='NW')
filename_Entry = tk.Label(frame_selectfile, width=52, textvariable=file_ID)
filename_Entry.grid(column=1, row=1, padx=5, pady=5, sticky='NW')
filename_Entry.configure(state='normal')
filelocation_Entry = tk.Entry(frame_selectfile, width=63, textvariable=location_id)
filelocation_Entry.grid(column=1, row=2, padx=5, pady=5, sticky='W')
filelocation_Entry.configure(background='palegreen', foreground='black')
unzip_status.set("")
label_unzipstatus = tk.Label(frame_selectfile, width=20, relief='flat', textvariable=unzip_status)
label_unzipstatus.grid(column=1, row=5, padx=5, pady=5, sticky='NSEW')
selectzip_button = tk.Button(frame_selectfile, width=20, text="Select Zip File",
command=lambda: self.upload_action(location_id, zip_filename, tmpdir))
selectzip_button.grid(column=1, row=3, padx=5, pady=3, ipady=3, sticky='SW')
unzip_button = tk.Button(frame_selectfile, width=20, text="Extract",
command=lambda: self.extract_nested_zip(databaseView, data_table_list,
location_id.get(), tmpdir, zip_filename,
site_id, False))
unzip_button.grid(column=1, row=3, padx=5, pady=3, ipady=3, sticky='NE')
# Creating LabelFrame in frame_unzip
upperframe = tk.LabelFrame(frame_selectfile, bd=0)
frame_selectfile.rowconfigure(0, weight=1)
frame_selectfile.columnconfigure(2, weight=1)
upperframe.grid(column=0, row=6, columnspan=2, sticky='W')
# middleframe = tk.LabelFrame(frame_selectfile, bd=5)
middleframe.configure(borderwidth=1)
frame_selectfile.columnconfigure(2, weight=1)
frame_selectfile.rowconfigure(1, weight=1)
middleframe.grid(column=0, row=7, columnspan=2, sticky="NSEW")
lowerframe = tk.LabelFrame(frame_selectfile, bd=0)
lowerframe.grid(column=0, row=7)
frame_selectfile.columnconfigure(2, weight=1)
frame_selectfile.rowconfigure(2, weight=0)
# Labels in frame_unzip
label18 = tk.Label(upperframe, text="Number of sites:", relief='flat')
label18.grid(column=0, row=0, padx=5, pady=5, sticky='W')
site_Entry = tk.Entry(upperframe, width=61, textvariable=site_id)
site_Entry.grid(column=1, row=0, padx=10, pady=5, sticky='E')
site_Entry.configure(state='normal', background='palegreen', foreground='black')
label_details = tk.Label(upperframe, text=" ", relief='flat')
label_details.grid(column=0, row=2, padx=5, pady=0, sticky='W')
databaseView.columnconfigure(2, weight=1)
databaseView.grid(column=0, row=0, columnspan=2, sticky="NSEW")
# Creating treeview in frame_unzip
vsb = Scrollbar(middleframe, orient="vertical", command=databaseView.yview())
hsb = Scrollbar(middleframe, orient="horizontal")
middleframe.columnconfigure(0, weight=1)
middleframe.rowconfigure(0, weight=1)
databaseView["show"] = "headings"
databaseView["columns"] = ("site", "panels", "tevs")
vsb.configure(command=databaseView.yview)
vsb.grid(column=1, row=0, sticky="NS")
# Treeview column headings
databaseView.heading("site", text="Site")
databaseView.column("site", anchor='w', width=250)
databaseView.heading("panels", text="Number of Panels")
databaseView.column("panels", anchor='center', width=150)
databaseView.heading("tevs", text="Number of TEVs")
databaseView.column("tevs", anchor='center', width=200)
findpd_btn = tk.Button(frame_checkpd, width=20, text="Find PDs",
command=lambda: self.run_pd_model_exe(tmpdir, zip_filename,parent_tree, tree))
findpd_btn.grid(column=0, row=0, padx=5, pady=5, sticky='E')
export_pdf_btn = tk.Button(frame_checkpd, width=20, text="Export to PDF",
command=lambda: self.export_to_pdf(tmpdir, location_id.get()))
export_pdf_btn.grid(column=1, row=0, padx=5, pady=5, sticky='E')
find_files_btn = tk.Button(frame_checkpd, width=20, text="Clear All",
command=lambda: self.clear_all_files(tmpdir,parent_tree,tree,databaseView))
find_files_btn.grid(column=2, row=0, padx=5, pady=5, sticky='W')
scrollbary = Scrollbar(frame_tree, orient=VERTICAL)
scrollbarx = Scrollbar(frame_tree, orient=HORIZONTAL)
parentframe = tk.LabelFrame(frame_checkpd, bd=0)
frame_checkpd.rowconfigure(2, weight=1)
frame_checkpd.columnconfigure(2, weight=1, )
parentframe.grid(column=0, row=1, columnspan=3, sticky='W')
# PARENT TREE
parent_tree = ttk.Treeview(parentframe,
columns=("1", "2",
"3", "4",
"5", "6",
"7", "8"),
selectmode="extended")
parent_tree.grid(row=1, column=0, pady=2, sticky=N + S + E + W)
#self.parent_tree.pack(expand=True, fill='both')
vsbb = Scrollbar(parentframe, orient="vertical", command=parent_tree.yview())
vsbb.configure(command=parent_tree.yview)
vsbb.grid(column=2, row=1, sticky="NS")
parent_tree.heading("#0", text="")
parent_tree.heading("1", text="File ID")
parent_tree.heading("2", text="Date")
parent_tree.heading("3", text="No")
parent_tree.heading("4", text="Engineer")
parent_tree.heading("5", text="Station")
parent_tree.heading("6", text="Voltage (kV)")
parent_tree.heading("7", text="Max dB")
parent_tree.heading("8", text="Max PD (%)")
# parent_tree.heading("8", text = "Panel No")
parent_tree.column('#0', stretch=YES, minwidth=0, width=5, anchor=CENTER)
parent_tree.column('#1', stretch=YES, minwidth=0, width=130, anchor=CENTER)
parent_tree.column('#2', stretch=YES, minwidth=0, width=130, anchor=CENTER)
parent_tree.column('#3', stretch=YES, minwidth=0, width=130, anchor=CENTER)
parent_tree.column('#4', stretch=YES, minwidth=0, width=130, anchor=CENTER)
parent_tree.column('#5', stretch=YES, minwidth=0, width=130, anchor=CENTER)
parent_tree.column('#6', stretch=YES, minwidth=0, width=130, anchor=CENTER)
parent_tree.column('#7', stretch=YES, minwidth=0, width=130, anchor=CENTER)
parent_tree.column('#8', stretch=YES, minwidth=0, width=130, anchor=CENTER)
# CHILD TREE
tree = ttk.Treeview(frame_tree,
columns=("1", "2", "3", "4"
, "5", "6", "7", "8"
, "9"),
selectmode="extended")
#yscrollcommand=scrollbary.set,
#xscrollcommand=scrollbarx.set)
tree.grid(row=0, column=0, pady=2, sticky=N + S + E + W)
# scrollbary.config(command=tree.yview)
# scrollbary.grid(row=0, column=1, pady=2, sticky=N + S)
#
# scrollbarx.config(command=tree.xview)
# scrollbarx.grid(row=2, column=0, sticky=W + E)
tree_vsb = Scrollbar(frame_tree, orient="vertical", command=tree.yview())
tree_hsb = Scrollbar(frame_tree, orient="horizontal")
tree_vsb.configure(command=tree.yview)
tree_vsb.grid(column=1, row=0, sticky="NS")
tree.heading("#0", text="")
tree.heading("1", text="Panel No")
tree.heading("2", text="TEV Name")
tree.heading("3", text="Component")
tree.heading("4", text="Sublocation")
tree.heading("5", text="Phase Ref Lock")
tree.heading("6", text="dB")
tree.heading("7", text="PRPD")
tree.heading("8", text="Pulse Wave")
tree.heading("9", text="PD %")
tree.column('#0', stretch=NO, minwidth=0, width=0, anchor=CENTER)
tree.column('#1', stretch=YES, minwidth=0, width=175, anchor=CENTER)
tree.column('#2', stretch=YES, minwidth=0, width=175, anchor=CENTER)
tree.column('#3', stretch=YES, minwidth=0, width=175, anchor=CENTER)
tree.column('#4', stretch=YES, minwidth=0, width=175, anchor=CENTER)
tree.column('#5', stretch=YES, minwidth=0, width=175, anchor=CENTER)
tree.column('#6', stretch=YES, minwidth=0, width=175, anchor=CENTER)
tree.column('#7', stretch=YES, minwidth=0, width=175, anchor=CENTER)
tree.column('#8', stretch=YES, minwidth=0, width=175, anchor=CENTER)
tree.column('#9', stretch=YES, minwidth=0, width=175, anchor=CENTER)
if __name__ == '__main__':
homePage = HomePage()
homePage.title("Waveform Identifier") # Window title
screen_width = homePage.winfo_screenwidth()
screen_height = homePage.winfo_screenheight()
width = 1600
height = 800
x = (screen_width / 2) - (width / 2)
y = (screen_height / 2) - (height / 2)
homePage.geometry("%dx%d+%d+%d" % (width, height, x, y))
homePage.resizable(1, 1)
homePage.mainloop()
Issues found
Wrong row number on frame_checkpd.rowconfigure(2, weight=1), it should be row 1.
Wrong sticky option on parentframe.grid(column=0, row=1, columnspan=3, sticky='W'), it should be 'NSEW'.
missing parentframe.rowconfigure(...) and parentframe.columnconfigure(...)
missing frame_tree.rowconfigure(...) and frame_tree.columnconfigure(...)
Below is the required changes to achieve it:
class tab_one(Frame):
def __init__(self, *args, **kwargs):
...
parentframe = tk.LabelFrame(frame_checkpd, bd=0)
frame_checkpd.rowconfigure(1, weight=1) ### row 2 -> 1
frame_checkpd.columnconfigure(2, weight=1, )
parentframe.grid(column=0, row=1, columnspan=3, sticky='NSEW') ### 'W' -> 'EW'
# PARENT TREE
parentframe.rowconfigure(1, weight=1) ### added
parentframe.columnconfigure(0, weight=1) ### added
...
# CHILD TREE
frame_tree.rowconfigure(0, weight=1) ### added
frame_tree.columnconfigure(0, weight=1) ### added
...
Result:
I've just managed to configure a scrollbar to properly scroll these widgets, but I'm still having an issue with the frame not fitting the canvas.
I have a bunch of labels that fill out a frame, but the frame doesn't stretch to fill the canvas in the way I want it to.
There was a solution to this on another question that suggested using .bind() and '<Configure' (see code) to have the canvas resized to fit the frame (I think), but there are two problems with that:
It's not working.
I want the frame to stretch to the canvas, not the canvas to shrink to the frame.
Any and all help is greatly appreciated. Pictures and relevant code below.
Thank you!
def list_talent():
global new_button, map_button, scrollbar, results_canvas, active_tab, results_frame
results_canvas.destroy()
scrollbar.destroy()
new_button.destroy()
map_button.destroy()
results_frame.destroy()
active_tab = ''
results_canvas = Canvas(root, width=1080)
results_canvas.grid(row=4, column=0, columnspan=7)
scrollbar = ttk.Scrollbar(root, orient=VERTICAL, command=results_canvas.yview)
scrollbar.grid(row=4, column=8, sticky=N+S)
results_frame = Frame(results_canvas)
results_frame_id = results_canvas.create_window((0, 0), window=results_frame, anchor="nw")
def frame_width(event):
canvas_width = event.width
results_canvas.itemconfig(results_frame_id, width=canvas_width)
results_canvas.bind('<Configure>', frame_width)
new_button = Button(root, text='New', font=('Times New Roman', 12), command=new_record)
new_button.grid(row=5, column=0)
map_button = Button(root, text='Map', font=('Times New Roman', 12))
map_button.grid(row=5, column=7)
results_title = ['ID', 'Name', 'Profession', 'City', 'Date Signed', 'Phone Number', 'Quick Note']
for index, text in enumerate(results_title):
res_title_label = Label(results_frame, text=text)
res_title_label.grid(row=0, column=index)
mycursor.execute("SELECT * FROM talents")
result = mycursor.fetchall()
for index, x in enumerate(result):
results_label = Label(results_frame, text=x[10])
results_label.grid(row=1+index, column=0, padx=10)
results_label = Label(results_frame, text=x[0])
results_label.grid(row=1+index, column=1, padx=10)
results_label = Label(results_frame, text=x[2])
results_label.grid(row=1+index, column=2, padx=10)
results_label = Label(results_frame, text=x[7])
results_label.grid(row=1+index, column=3, padx=10)
results_label = Label(results_frame, text=x[11])
results_label.grid(row=1+index, column=4, padx=10)
results_label = Label(results_frame, text=x[2])
results_label.grid(row=1+index, column=5, padx=10)
results_label = Label(results_frame, text=x[0])
results_label.grid(row=1+index, column=6, padx=10)
edit_button = Button(results_frame, text='E', font=('Times New Roman', 12))
edit_button.grid(row=1+index, column=7)
view_button = Button(results_frame, text='V', font=('Times New Roman', 12))
view_button.grid(row=1+index, column=8)
results_canvas.configure(yscrollcommand=scrollbar.set)
results_frame.bind('<Configure>', lambda e: results_canvas.configure(scrollregion=results_canvas.bbox("all")))
active_tab = 'Talent'
i want to open the menu_frame by clicking the login_button but the frame won't come up and there are no error messages showing up. its my first time and im so lost
ive tried to google how to fix this problem but from what ive read, it seems to me that there are no errors or any reason for this code to not function properly. please help :(
from tkinter import *
window = Tk()
window.title("EL TALLO")
window.geometry("700x490")
window.config(background="#FFF8E5")
#회원가입
def register_frame():
register_frame = Frame(
window,
bd=2,
bg='#FFF8E5',
relief=SOLID,
padx=10,
pady=10
)
Label(
register_frame,
text="ID입력",
bg='#CCCCCC',
).grid(row=0, column=0, sticky=W, pady=10)
Label(
register_frame,
text="비밀번호 입력",
bg='#CCCCCC',
).grid(row=5, column=0, sticky=W, pady=10)
newlyset_id = Entry(
register_frame
)
newlyset_pw = Entry(
register_frame,
show='*'
)
register_btn = Button(
register_frame,
width=15,
text='회원가입',
relief=SOLID,
cursor='hand2',
command=register_frame.destroy
)
newlyset_id.grid(row=0, column=1, pady=10, padx=20)
newlyset_pw.grid(row=5, column=1, pady=10, padx=20)
register_btn.grid(row=7, column=1, pady=10, padx=20)
register_frame.pack()
register_frame.place(x=220, y=150)
def new_id(): #new_id에 newlyset_id에 입력한 값을 저장
new_id = newlyset_id.get()
def new_pw(): #new_pw에 newlyset_pw에 입력한 값을 저장
new_pw = newlyset_pw.get()
#메뉴화면
def menu_frame():
menu_frame = Frame(
window,
bd=2,
bg='#FFF8E5',
relief=SOLID,
padx=10,
pady=10
)
label1 = Label(menu_frame, text = "EL TALLO", bg="lightgreen",width=10, height=1, font=(15))
label1.pack()
btn1 = Button(menu_frame, text = "play game", bg="gray", width=15, height=1)
btn1.pack()
btn2 = Button(menu_frame, text = "How to play", bg="gray", width=15, height=1)
btn2.pack()
btn3 = Button(menu_frame, text = "Settings", bg="gray", width=15, height=1)
btn3.pack()
def btncmd():
print("게임이 종료되었습니다")
btn4 = Button(menu_frame, text = "END GAME", command=btncmd, bg="lightgreen", width=15, height=1)
btn4.pack()
label1.place(x=50, y=50)
btn1.place(x=50, y=100)
btn2.place(x=50, y=150)
btn3.place(x=50, y=200)
btn4.place(x=50, y=250)
#로그인
Label(
window,
text="아이디 입력",
bg='#CCCCCC',
).place(x=230, y=170)
id_tf = Entry(
window,
).place(x=330, y=170)
def id(): #id에 id_tf에 입력한 값을 저장
id = id_tf.get()
Label(
window,
text="비밀번호 입력",
bg='#CCCCCC',
).place(x=230, y=220)
pw_tf = Entry(
window,
).place(x=330, y=220)
def pw(): #pw에 pw_tf에 입력한 값을 저장
pw = pw_tf.get()
#회원가입 버튼
registerbutton = Button(
window,
width=15,
text="회원가입",
bg="#CCCCCC",
cursor='hand2',
command=register_frame
)
registerbutton.place(x=360, y=270)
#로그인 버튼
loginbutton = Button(
window,
width=15,
text="로그인",
bg="#CCCCCC",
cursor='hand2',
command=menu_frame
)
loginbutton.place(x=230, y=270)
window.mainloop()
You didn't pack the menu_frame and the indentation of def btncmd() was wrong.
That is:
btn3 = Button(menu_frame, text = "Settings", bg="gray", width=15, height=1)
btn3.pack()
menu_frame.pack()
def btncmd():
print("게임이 종료되었습니다")
Very simple, don't be impressed by the size of the code.
I want to do something very simple (well, not for me, since I'm asking for help here) put the location of the open file in the red square on the screen:
Screen
import tkinter as tk
from tkinter.filedialog import askopenfilename
from tkinter import messagebox
def OpenFile_AntiDuplicate():
global antiduplicate_file
mainframe = tk.Frame(bg='#1c2028')
antiduplicate_file = askopenfilename(initialdir="/",
filetypes =(("Text file", "*.txt"),("All files","*.*")),
title = "Open text file"
)
fichier_dir = tk.Label(mainframe, text=antiduplicate_file).pack()
try:
with open(antiduplicate_file,'r') as UseFile:
print(antiduplicate_file)
except:
print("Non-existent file")
def RUN_AntiDuplicate():
try:
with open(antiduplicate_file,'r') as UseFile:
print(antiduplicate_file)
except:
error1 = tk.messagebox.showerror("ERROR", "No files exist!")
#----------------------------------------------------------
class HoverButton(tk.Button):
def __init__(self, master, **kw):
tk.Button.__init__(self,master=master,**kw)
self.defaultBackground = self["background"]
self.bind("<Enter>", self.on_enter)
self.bind("<Leave>", self.on_leave)
def on_enter(self, e):
self['background'] = self['activebackground']
def on_leave(self, e):
self['background'] = self.defaultBackground
#----------------------------------------------------------
def Anti_Duplicate():
mainframe = tk.Frame(bg='#1c2028')
mainframe.grid(row=0, column=0, sticky='nsew')
bouton_1 = HoverButton(mainframe, font=("Arial", 10), text="Back",
background='#000000', fg='white', borderwidth=2,
activebackground='#202124', activeforeground='#CF3411',
relief='ridge', command=mainframe.destroy)
bouton_1.place(x=520, y=300)
open_button = HoverButton(mainframe, font=("Arial", 10), text="Open File..",
background='#000000', fg='white', borderwidth=2,
activebackground='#202124', activeforeground='#1195cf',
relief='ridge', command = OpenFile_AntiDuplicate)
open_button.place(x=284.3, y=200, anchor='n')
run_button = HoverButton(mainframe, font=("Arial", 20), text="RUN",
background='#000000', fg='white', borderwidth=2,
activebackground='#202124', activeforeground='#11CF6D',
relief='ridge', command = RUN_AntiDuplicate)
run_button.place(x=50, y=330, anchor='s')
bouton_2 = tk.Button(mainframe, font=("Arial", 10),
text="The purpose of this tool is to remove duplicate lines from a text file.",
background='#202124', fg='#1195cf', borderwidth=2,
activebackground= '#202124', activeforeground='#1195cf', relief='sunken')
bouton_2.place(relx=.5, y=50, anchor='n')
bouton_1 = tk.Button(mainframe, font=("Arial", 15), text="Anti-Duplicate",
background='#202124', fg='#1195cf', borderwidth=2,
activebackground='#202124', activeforeground='#1195cf', relief='sunken')
bouton_1.pack(side= "top", padx= 5, pady=5, ipadx= 30, anchor="n")
#----------------------------------------------------------
def main_menu():
root = tk.Tk()
screenn_x = int(root.winfo_screenwidth())
root.config(background='#1c2028')
screenn_y = int(root.winfo_screenheight())
root.title("ComboKit v0.0.1")
root.minsize(570, 340)
root.resizable(0,0)
windowss_x = 570
windowss_y = 340
possX = (screenn_x // 2) - (windowss_x // 2)
possY = (screenn_y // 2) - (windowss_y // 2)
geoo = "{}x{}+{}+{}".format(windowss_x, windowss_y, possX, possY)
root.geometry(geoo)
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
mainframe = tk.Frame(root, bg='#1c2028')
mainframe.grid(row=0, column=0, sticky='n')
main_fusion_bouton = HoverButton(mainframe, font=("Arial", 15), text="Fusion",
background='#000000', fg='white', borderwidth=2,
activebackground='#202124', activeforeground='#1195cf',
relief='ridge', command=None)
main_fusion_bouton.pack(side= "left", padx= 5, pady=5, ipadx= 10, anchor="n")
main_antiduplicate_bouton = HoverButton(mainframe, font=("Arial", 15), text="Anti-Duplicate",
background='#000000', fg='white', borderwidth=2,
activebackground='#202124', activeforeground='#1195cf',
relief='ridge', command=Anti_Duplicate)
main_antiduplicate_bouton.pack(side= "left", padx= 5, pady=5, ipadx= 30)
main_split_button = HoverButton(mainframe, font=("Arial", 15), text="Split",
background='#000000', fg='white', borderwidth=2,
activebackground='#202124', activeforeground='#1195cf',
relief='ridge', command=None)
main_split_button.pack(side= "left", padx= 5, pady=5, ipadx= 19, anchor="n")
root.mainloop()
main_menu()
So here's my code allows you to use 3 tools:
"Split" / "Anti-Duplicate" / "Merge"
At the moment I'm working on the "Anti-Duplicate" so it's on this Frame() where the text should be displayed.
I've already done everything, even the button to open the file explorer, but for the moment the location of the file is only displayed in the cmd.
Thank you very much!
The location of the file does not show up because you created a new frame to hold the label fichier_dir inside OpenFile_AntiDuplicate() and you did not call any layout function on the frame, so the frame will not be shown.
Better create the label fichier_dir inside Anti_Duplicate() and pass it to OpenFile_AntiDuplicate() function:
def Anti_Duplicate():
...
fichier_dir = tk.Label(mainframe, bg='#1c2028', fg='white')
fichier_dir.place(relx=0.5, y=170, anchor='n')
open_button = HoverButton(mainframe, font=("Arial", 10), text="Open File..",
background='#000000', fg='white', borderwidth=2,
activebackground='#202124', activeforeground='#1195cf',
relief='ridge', command = lambda: OpenFile_AntiDuplicate(fichier_dir))
...
And update OpenFile_AntiDuplicate(...):
def OpenFile_AntiDuplicate(fichier_dir):
global antiduplicate_file
antiduplicate_file = askopenfilename(initialdir="/",
filetypes =(("Text file", "*.txt"),("All files","*.*")),
title = "Open text file"
)
fichier_dir['text'] = antiduplicate_file
...
delete(0, END) does not work for some reason. It does not give any error messages and the rest of the code seems fine. The delete(0, END) won't delete the 0's I get in my entry boxes from the intvar and I cant figure out why it won't work. I'm using delete in another code and it works there. Could anyone help me out?
The code i got problem with.
part1_entry = tk.Entry(Frame1, font=('Helvetica', 12, 'bold'),
textvariable=self.a3, validate = 'key', validatecommand = vcmd, width = 11)
part1_entry.grid(column=0, row=6, sticky=(W), columnspan=1)
part1_entry.delete(0, END)
part2_entry = tk.Entry(Frame1, font=('Helvetica', 12, 'bold'),
textvariable=self.a5, validate = 'key', validatecommand = vcmd, width = 11)
part2_entry.grid(column=0, row=6, sticky=(E), columnspan=1)
part2_entry.delete(0, END)
Here is my code.
import tkinter as tk
from tkinter import ttk
import io
from tkinter import filedialog
E=tk.E
W=tk.W
N=tk.N
S=tk.S
VERTICAL=tk.VERTICAL
END=tk.END
class Demo1(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.master = master
self.Frame = tk.Frame(self.master, borderwidth=10)
self.Frame.grid(column=0, row=0, sticky=(N, W, E, S))
button1 = tk.Button(self.Frame, text="Special Rk märkning", command=self.new_window, width = 25)
button1.grid(column=0, row=0, sticky=(W, E), columnspan=4)
button2 = tk.Button(self.Frame, text="Billerud kabelmärkningar", command=self.new_window, width = 25)
button2.grid(column=0, row=1, sticky=(W, E), columnspan=4)
def new_window(self):
Billerud(self)
class Billerud:
def __init__(self, master):
self.master = master
top1 = tk.Toplevel()
top1.title("Billerud")
top1.resizable(width=False, height=False)
#fönster designern här bästems fönster ramar, rader och columner
Frame1 = tk.Frame(top1)
Frame1.grid(column=1, row=0, sticky=(N, W, E, S), padx=5, pady=5)
Frame1.columnconfigure(0, weight=1)
Frame1.rowconfigure(0, weight=1)
#Koden är en del av entry's endast nummer restriktion
vcmd = (Frame1.register(self.validate),
'%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
#create text editor
self.text_entry = tk.Text(Frame1, width=25,height=20)
self.text_entry.grid(column=0, row=0, sticky=(W, E))
scrollbar = tk.Scrollbar(Frame1, orient=VERTICAL)
scrollbar.grid(column=0, row=0, sticky=(N, E, S))
# koppla ihop listbox med scrollbar
self.text_entry.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=self.text_entry.yview)
self.a1 = tk.StringVar()
self.a2 = tk.StringVar()
self.a3 = tk.IntVar()
self.a4 = tk.StringVar()
self.a5 = tk.IntVar()
text1 = tk.Label(Frame1, text="Kabelnamn:", font=("Helvetica", 12, "bold")).grid(column=0, row=1, sticky=(W), columnspan=2)
Kabelnamn_entry = tk.Entry(Frame1, font=('Helvetica', 12, 'bold'), textvariable=self.a1)
Kabelnamn_entry.grid(column=0, row=2, sticky=(W, E), columnspan=2)
text2 = tk.Label(Frame1, text="Kabelnummer:", font=("Helvetica", 12, "bold")).grid(column=0, row=3, sticky=(W), columnspan=2)
Kabelnummer_entry = tk.Entry(Frame1, font=('Helvetica', 12, 'bold'), textvariable=self.a2)
Kabelnummer_entry.grid(column=0, row=4, sticky=(W, E), columnspan=2)
text3 = tk.Label(Frame1, text="Parter från: Till:", font=("Helvetica", 12, "bold")).grid(column=0, row=5, sticky=(W), columnspan=1)
part1_entry = tk.Entry(Frame1, font=('Helvetica', 12, 'bold'), textvariable=self.a3, validate = 'key', validatecommand = vcmd, width = 11)
part1_entry.grid(column=0, row=6, sticky=(W), columnspan=1)
part1_entry.delete(0, END)
part2_entry = tk.Entry(Frame1, font=('Helvetica', 12, 'bold'), textvariable=self.a5, validate = 'key', validatecommand = vcmd, width = 11)
part2_entry.grid(column=0, row=6, sticky=(E), columnspan=1)
part2_entry.delete(0, END)
button1 = tk.Button(Frame1, text="Make", command=self.funktion, width = 16)
button1.grid(column=0, row=7, sticky=(W, E), columnspan=4)
button2 = tk.Button(Frame1, text="Spara", command=self.file_save, width = 16)
button2.grid(column=0, row=8, sticky=(W, E), columnspan=4)
top1.update()
top1.resizable(width=False, height=False)
top1.mainloop()
def validate(self, action, index, value_if_allowed,
prior_value, text, validation_type, trigger_type, widget_name):
if text in '0123456789.-+':
try:
float(value_if_allowed)
return True
except ValueError:
return False
else:
return False
def file_save(self):
file = tk.filedialog.asksaveasfile(defaultextension=".txt", mode='wt', filetypes = (("txt files","*.txt"),("all files","*.*")))
if file:
data = self.text_entry.get('1.0', END+'-1c')
file.write(data)
file.close()
def funktion(self):
value1 = (self.a1.get())
value2 = (self.a2.get())
value3 = (self.a3.get())
value4 = (self.a4.get())
value5 = (self.a5.get())
for parts in range(value3-1, value5):
print('{}-{}-{}-{}\n'.format(value1, value2, parts+1, parts+1))
self.text_entry.insert(END, '{}-{}-{}-{}\n'.format(value1, value2, parts+1, parts+1))
self.a4.set('{}-{}-{}-{}\n'.format(value1, value2, parts+1, parts+1))
def close_windows(self):
self.master.destroy()
def main():
root = tk.Tk()
app = Demo1(root)
root.protocol("WM_DELETE_WINDOW")
root.mainloop()
if __name__ == '__main__':
main()
lucky for you I have way too much free time at the moment.
Try using:
self.a3.set("")
self.a5.set("")
maybe someone who actually knows tkinter will be able to help more.
I think you should try:
part1_entry.delete(0, 'end')
part2_entry.delete(0, 'end')