I have a problem with scrolling the horizontal bar. When I add another column is the whole
I'm leaving the window in which I display it. Is it possible to set the size of the treeview permanently and scroll the columns with the horizontal bar?
The screen may be too small at present. To display the data content.
Here is my source
def wczytaj_dane(page):
ok = Toplevel()
width_of_window = 1030
height_of_window = 570
screen_width = ok.winfo_screenwidth()
screen_height = ok.winfo_screenheight()
x_coordinate = (screen_width/2) - (width_of_window/2)
y_coordinate = (screen_height/2) - (height_of_window/2)
ok.geometry("%dx%d+%d+%d" % (width_of_window, height_of_window, x_coordinate, y_coordinate))
"""Polączenie z bazą danych oraz pobieranie danych"""
connection = pymysql. connect ( host = '192.168.10.100' ,
database = 'tester_produkcja' ,
user = 'marcin' ,
password = 'marcin96' )
try:
with connection . cursor () as cursor :
sql= "SELECT * FROM `Historia` WHERE `Poczernin_kod_Produktu`='DP^8E0E1^0005'"
cursor.execute ( sql,)
result_dpcode = cursor.fetchall () #fetchone ()
""" zamiana krotki(tuple) na liczbę całkowitą"""
#result_dp = int(result_dpcode[0])
finally:
connection.close()
tree = ttk.Treeview(ok,height=5)
tree["columns"]=("one","two","three","four","five","six","seven","eight","nine","ten","ten1","ten2","ten3","ten4","ten5",
"ten6","ten7")
tree.column("#0", width=40)
tree.column("one", width=100 )
tree.column("two", width=50)
tree.column("three", width=220)
tree.column("four", width=50 )
tree.column("five", width=50)
tree.column("six", width=50)
tree.column("seven", width=50)
tree.column("eight", width=50)
tree.column("nine", width=50)
tree.column("ten", width=50)
tree.column("ten1", width=50)
tree.column("ten2", width=70)
tree.column("ten3", width=70)
tree.column("ten4", width=125)
tree.column("ten5", width=120)
tree.column("ten6", width=100)
tree.column("ten7", width=100)
tree.heading("#0", text="Lp.")
tree.heading("one", text="Godzina/Data")
tree.heading("two", text="KTM")
tree.heading("three",text="Nazwa Produktu")
tree.heading("four",text="Funkcja")
tree.heading("five",text="PW")
tree.heading("six", text="VAC")
tree.heading("seven",text="WATT")
tree.heading("eight",text="ŁAD")
tree.heading("nine",text="ROZŁ")
tree.heading("ten",text="VDC")
tree.heading("ten1",text="Uwagi")
tree.heading("ten2",text="Pracownik")
tree.heading("ten3",text="Inspektor")
tree.heading("ten4",text="Poprawność Montażu")
tree.heading("ten5",text="Wygląd zewnętrzny")
tree.heading("ten6",text="Wygląd zewnętrzny")
tree.heading("ten7",text="Wygląd zewnętrzny")
cpt = 0
for row in result_dpcode:
tree.insert('','end', text=str(cpt), values=(row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8],
row[9],row[10],row[11],row[12],row[13],row[14],row[15] ))
cpt +=1
ysb = ttk.Scrollbar (ok, orient = 'vertical', command = tree.yview)
xsb = ttk.Scrollbar (ok, orient = 'horizontal', command = tree.xview)
tree.grid(row=0,column=0)
ysb.grid (row = 0, column = 1, sticky = N+S)
xsb.grid (row = 1,column = 0, sticky = E+W)
tree.configure (yscroll = ysb.set)
tree.configure (xscroll = xsb.set)
Related
I have created a tkinter GUI using a for loop. it has some labels, entry boxes and 2 buttons. One buttons pull whatever has been entered in the entry boxes and second button populate the entry boxes based on a list. First button is working fine, but second button (FETCH button) gives this error "Entry' object has no attribute 'set'" . Can someone help and confirm what am I doing wrong?
below is the code
from tkinter import *
bg_color_2 = "#d9ffff"
background_color = bg_color_2
button_color = "#ffe08a"
white_font_color = "##ffffff"
black_font_color = "000000"
relief_type = "ridge"
width_of_window = 938
height_of_window = 833
root = Tk()
root.configure(bg= background_color)
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x_coordinate = (screen_width/2) - (width_of_window/2)
y_coordinate = (screen_height/2) - (height_of_window/2)
root.geometry("%dx%d+%d+%d" % (width_of_window, height_of_window, x_coordinate, y_coordinate))
def send():
rule_entry = []
for entries in my_entries:
rule_entry.append(entries.get())
def fetch():
rule_label_list = ['test1', 'test2', 'test3', 'test4', 'test5', 'test5', 'test6', 'test7', 'test8', 'test9', 'test10', 'test11', 'test12', 'test13', 'test14', 'test15', 'test16', 'test17', 'test18']
i = 0
print(my_entries)
for a in my_entries:
a.set(rule_label_list[i])
i + i + 1
root.title("Result Rule")
root.minsize(width_of_window, height_of_window)
root.maxsize(width_of_window, height_of_window)
rule_label_list = ['label1', 'label2', 'label3', 'label4', 'label5', 'label5', 'label6', 'label7', 'label8', 'label9', 'label10', 'label11', 'label12', 'label13', 'label14', 'label15', 'label16', 'label17', 'label18']
my_entries = []
for a in range(0,19):
my_label = Label(root, text=rule_label_list[a], fg= 'black', bg= bg_color_2, justify = LEFT, width=15,font=("bold", 10), anchor=W, borderwidth = 2)
my_label.grid(row=a, column=0, pady=5, padx=5)
my_entry_box = Entry(root, fg= 'black', bg='#FFFFFF', justify = LEFT, width=65,font=("bold", 10))
my_entry_box.grid(row=a, column=1, columnspan = 4, pady=5)
my_entries.append(my_entry_box)
Button(root, text='SEND', bg='#ffc200',fg='black', font=("bold", 10), width=15, height = 1,command = send).grid(row=20,column=0,pady=5, padx=5)
Button(root, text='FETCH', bg='#ffc200',fg='black', font=("bold", 10), width=15, height = 1,command = fetch).grid(row=20,column=1,pady=5, padx=5)
root.mainloop()
a = DoubleVar()
a.set(rule_label_list[i])
Try to add DoubleVar in line 34.
It helped me
I want to pass a button name to tkinter as a variable. This method works for Text fields, but not for buttons in my code.
I am building a gui app and I want to have a generic clear function that zaps a text entry field and resets a button from NORMAL to DiSABLED.
There are multiple buttons and fields, hence the desire to make this generic.
For the code I have, the buttons are present with the exception of clear all.
I am setting the variable w_button to the specific name of the (existing) button based on what is passed to the function.
def switch_clear(elem_type):
if elem_type == 'scn':
w_button = 'b_clear_scn'
clear_field = 'scn_file_entry'
print ('scenario')
elif elem_type == 'sol2':
w_button = 'b_clear_sol2'
clear_field = 'sol2_file_entry'
print ('sol2')
elif elem_type == 'mdl':
w_button = 'b_clear_mdlList'
clear_field = 'mdlList_file_entry'
print ('mdl')
elif elem_type == 'all':
print ('clear all TBD')
return()
if w_button["state"] == NORMAL:
clear_field.delete(0, END)
w_button["state"] = DISABLED
return()
Here's what happens:
C:\utils>my_frame3.py
scenario
Traceback (most recent call last):
File "C:\utils\my_frame3.py", line 127, in <module>
b_clear_scn = Button(first_frame, text = "Clear scenario", command = switch_clear('scn'), height = 2, state=DISABLED)
File "C:\utils\my_frame3.py", line 100, in switch_clear
if w_button["state"] == NORMAL:
TypeError: string indices must be integers
C:\utils>
I realize I could duplicate and push the clear operations into the if/elif statements, and I may have to live with that but - is it possible to reference buttons as variables? How can I do this?
Complete code as requested below. The preview is a mess despite using the code widget, but in my file lines are correctly formatted (notepad++). Tx
import os, sys
from tkinter import *
from tkinter import messagebox
from tkinter import filedialog
root2 = Tk()
root2.title('Model Processing')
root2.geometry('{}x{}'.format(512, 400))
# colors
color1 = 'light cyan'
color2 = 'gold'
color3 = 'RosyBrown1'
color4 = 'lavender'
color5 = 'linen'
bg_color = 'azure'
# number of items to process; until >1 OK is disabled; if >1 OK is enabled TBD
l_to_do = [] # items to process; scn, sol2, modelList, installed models
# functions/commands
def callback():
print ('A button was clicked.')
return;
def my_exit():
result = messagebox.askquestion("Cancel Model Processing", "Are you sure?", icon='warning')
if result == 'yes':
root2.quit()
else: # user changed mind
pass
def choose_import_file(str_ftype):
which_field = ''
which_clear_btn = ''
ftype = str_ftype
mdl_opts = {}
if ftype == 'scn':
title_msg = 'Choose a scenario file'
mdl_opts['filetypes'] = [('Supported types', ('.scn')),
('scenario files',('.scn'))]
which_field = scn_file_entry
which_clear_btn = 'b_clear_scn'
elif ftype == 'sol2':
title_msg = 'Choose a SOL2 file'
mdl_opts['filetypes'] = [('Supported types', ('.txt')),
('sol2 files',('.txt'))]
which_field = sol2_file_entry
elif ftype == 'mdllist':
title_msg = 'Choose a ModelList file'
print ('TBD: ModelList file')
file_input = filedialog.askopenfilename(title = title_msg, **mdl_opts)
if file_input == '':
print ('error or cancelled by user')
return
else:
f_inp_file = os.path.basename(file_input)
f_inp_file_base = str(file_input.split('.')[0])
f_inp_file_ext = str.lower(str(file_input.split('.')[1]))
f_inp_d_name = os.path.dirname(file_input)
print('File chosen:', f_inp_file_base)
# populate scenario file field
which_field.insert(INSERT,file_input)
which_clear_btn["state"] = NORMAL
# define appropriate clear button active
# define_clear_btn.configure(state = ACTIVE)
return
def switch_clear(elem_type):
if elem_type == 'scn':
if b_clear_scn["state"] == NORMAL:
scn_file_entry.delete(0, END)
b_clear_scn["state"] = DISABLED
elif elem_type == 'sol2':
f b_clear_sol2["state"] == NORMAL:
clear_field = 'sol2_file_entry'
b_clear_sol2["state"] = DISABLED
elif elem_type == 'mdl':
if b_clear_mdlList["state"] == NORMAL:
clear_field = 'mdlList_file_entry'
b_clear_mdlList["state"] = DISABLED
elif elem_type == 'all':
print ('clear all TBD')
return()
return()
# create all of the main containers
first_frame = Frame(root2, bg=color5, width = 512, height=90, pady=10)
second_frame = Frame(root2, bg=color5, width = 512, height=90, pady=10)
third_frame = Frame(root2, bg=color5, width=512, height=90, pady=10)
fourth_frame = Frame(root2, bg=color5, width = 512, height = 90, pady=10)
# layout all of the main containers
root2.grid_rowconfigure(3, weight=1)
root2.grid_rowconfigure(2, weight=1)
root2.grid_rowconfigure(1, weight=1)
root2.grid_columnconfigure(0, weight=1)
first_frame.grid(row=0, sticky="ew")
second_frame.grid(row=1, sticky="ew")
third_frame.grid(row=2, sticky="ew")
fourth_frame.grid(row = 3, sticky="e")
# create the widgets for the first frame
#scn_label = Label(first_frame, text = 'Scenario file')
scn_file_entry = Entry(first_frame, background=bg_color, width = 50)
b_choose_scn = Button(first_frame, text = "Choose a scenario..", command = lambda: choose_import_file('scn'), height = 2)
b_clear_scn = Button(first_frame, text = "Clear scenario", command = switch_clear('scn'), height = 2, state=DISABLED)
# layout the widgets in the first frame
#scn_label.grid(row = 0, column = 0, padx = (10,50), pady=5)
scn_file_entry.grid(row = 0, column = 1, padx = (10,10))
b_choose_scn.grid(row=0, column=0, padx = (10,10), sticky=W)
b_clear_scn.grid(row=2, column=0, padx = (10,10), sticky=W)
# second frame
# sol2_label = Label(second_frame, text = 'Sol2 file')
sol2_file_entry = Entry(second_frame, background=bg_color, width = 50)
b_choose_sol2 = Button(second_frame, text = "Choose SOL2 file..", command = lambda: choose_import_file('sol2'), height = 2)
b_clear_sol2 = Button(second_frame, text = "Clear SOL2", command = switch_clear('sol2'), height = 2, state=DISABLED)
# layout the widgets in the second frame
# sol2_label.grid(row = 0, column = 0, padx = (10,50), pady=5)
sol2_file_entry.grid(row = 0, column = 1, padx = (10,10), sticky=EW)
b_choose_sol2.grid(row=0, column=0, padx = (10,10), sticky=W)
b_clear_sol2.grid(row=2, column=0, padx = (10,10), sticky=W)
# third frame
# mdlList_label = Label(third_frame, text = 'ModelList.txt file')
mdlList_file_entry = Entry(third_frame, background=bg_color, width = 50)
b_choose_mdlList = Button(third_frame, text = "Choose ModelList.txt file..", command = callback, height = 2)
b_clear_mdlList = Button(third_frame, text = "Clear ModelList", command = callback, height = 2, state=DISABLED)
# layout the widgets in the third frame
#mdlList_label.grid(row = 0, column = 0, padx = (10,10), pady=5, sticky = 'ns')
mdlList_file_entry.grid(row = 0, column = 1, padx = (10,10), sticky=EW)
b_choose_mdlList.grid(row=0, column=0, padx = (10,10), sticky=W)
b_clear_mdlList.grid(row=2, column=0, padx = (10,10), sticky=W)
#####################################################################
# create bottom widgets
#####################################################################
clear_all = Button(fourth_frame, text='Clear All', padx = '5', command = callback, height = 2, state=DISABLED)
ok_btn = Button(fourth_frame, text='OK', padx = '5', command = callback, height = 2, state=DISABLED)
cancel_btn = Button(fourth_frame, text='Cancel', height = 2, padx = '12', command = my_exit)
#####################################################################
# layout the bottom widgets
#####################################################################
clear_all.grid(row = 0, column = 2, sticky = 'e')
ok_btn.grid(row = 0, column = 3, sticky = 'e')
cancel_btn.grid(row = 0, column = 4, sticky = 'e')
# commands/bindings
root2.mainloop()
I believe this is what you are trying to do. The below is fully commented with explanations. switch_clear becomes entirely unnecessary with this method. The buttons directly clear their corresponding entry in their command, and Entry validation takes care of the corresponding button state.
Note: I wrote all of this before you posted your full code
import tkinter as tk
root = tk.Tk()
root.geometry('400x400')
#toggle the state of buttons based on entry text length
def toggle_button(name, text):
global btn_switch
btn_switch[name]['state'] = 'normal' if len(text) else 'disabled'
return True
#to hold the buttons so they are easy to position
#just for this example
buttons = tk.Frame(root)
buttons.pack(side='top', anchor='nw')
#create a tcl wrapper for the validate command
vcmd = tk.Widget.register(root, toggle_button)
#mock-up of your entries ~ validate on key press. send widget name and full text to vcmd
scn_file_entry = tk.Entry(root, width=20)
scn_file_entry.configure(validate="key", validatecommand=(vcmd, '%W', '%P'))
scn_file_entry.pack(side='left', anchor='nw')
sol2_file_entry = tk.Entry(root, width=20)
sol2_file_entry.configure(validate="key", validatecommand=(vcmd, '%W', '%P'))
sol2_file_entry.pack(side='left', anchor='nw')
mdlList_file_entry = tk.Entry(root, width=20)
mdlList_file_entry.configure(validate="key", validatecommand=(vcmd, '%W', '%P'))
mdlList_file_entry.pack(side='left', anchor='nw')
#mock-up of your buttons ~ delete the entry text in a lambda and let entry validation handle the button state
b_clear_scn = tk.Button(buttons, text="scn", state='disabled')
b_clear_scn.configure(command=lambda: scn_file_entry.delete(0, 'end'))
b_clear_scn.pack(side='left', anchor='nw')
b_clear_sol2 = tk.Button(buttons, text="sol2", state='disabled')
b_clear_sol2.configure(command=lambda: sol2_file_entry.delete(0, 'end'))
b_clear_sol2.pack(side='left', anchor='nw')
b_clear_mdlList = tk.Button(buttons, text="mdl", state='disabled')
b_clear_mdlList.configure(command=lambda: mdlList_file_entry.delete(0, 'end'))
b_clear_mdlList.pack(side='left', anchor='nw')
#create a dictionary of 'widget name':corresponding button, for toggle_button to reference
btn_switch = {
f'{scn_file_entry}':b_clear_scn,
f'{sol2_file_entry}':b_clear_sol2,
f'{mdlList_file_entry}':b_clear_mdlList,
}
root.mainloop()
yesterday i wrote this program, i started programming with python recently. i decided to do a program with the gui, a program for the ordering of the panini and use the qrcode for read what is the order, i used tkinter and pyqrcode as u can see in the code. i think that the problem is the checkbox, because it does not give me any result, so the qr code is null and the code dont work. i 'm here for help to solve this problem and some suggestions to improve programming, thanks
import tkinter as tk
window = tk.Tk()
window.geometry("500x500")
window.title("Ordina panino")
window.resizable(False,False)
window.configure(background='Yellow')
frame=tk.Frame(window) #frame panino 1
frame.pack(side = tk.TOP, pady= 20)
frame2=tk.Frame(window) #frame descrizione panino 1
frame2.pack(side = tk.TOP)
frame3=tk.Frame(window) #frame panino 2
frame3.pack(side = tk.TOP, pady= 20)
frame4=tk.Frame(window) #frame descrizione panino 2
frame4.pack(side = tk.TOP)
frame5=tk.Frame(window) #frame panino 3
frame5.pack(side = tk.TOP, pady= 20)
frame6=tk.Frame(window) #frame descrizione panino 3
frame6.pack(side = tk.TOP)
frame7=tk.Frame(window, pady= 20) #frame panino 4
frame7.pack(side = tk.TOP)
frame8=tk.Frame(window) #frame descrizione panino 4
frame8.pack(side = tk.TOP)
frame9=tk.Frame(window, pady=20) #frame Bottone
frame9.pack(side = tk.TOP)
#//////////////////////////////////////// PANINO1
CheckVar1 = tk.IntVar()
radiobutton1= tk.Checkbutton(frame, variable= CheckVar1, padx= 10, )
radiobutton1.pack( side = tk.LEFT )
panino1 = tk.Label(frame, text = 'panino1', padx=20)
panino1.pack( side = tk.LEFT)
numeropanini1 =tk.Spinbox(frame,from_=0, to=10)
numeropanini1.pack( side = tk.RIGHT )
testodescpanino1= "Ingredienti panino 1: ###############,##########,\n #############,##########"
descrizionepanino1 = tk.Label(frame2, text = testodescpanino1)
descrizionepanino1.pack( side = tk.TOP)
#//////////////////////////////////////// PANINO 2
CheckVar2 = tk.IntVar()
radiobutton2= tk.Checkbutton(frame3, variable = CheckVar2, padx=10)
radiobutton2.pack( side = tk.LEFT )
panino2 = tk.Label(frame3, text = 'panino2', padx= 20)
panino2.pack( side = tk.LEFT)
numeropanini2 =tk.Spinbox(frame3, from_=0, to=10)
numeropanini2.pack( side = tk.RIGHT )
testodescpanino2= "Ingredienti panino 2: ###############,##########,\n #############,##########"
descrizionepanino2 = tk.Label(frame4, text = testodescpanino2)
descrizionepanino2.pack( side = tk.TOP)
#//////////////////////////////////////// PANINO 3
CheckVar3 = tk.IntVar()
radiobutton3= tk.Checkbutton(frame5, variable= CheckVar3, padx=10)
radiobutton3.pack( side = tk.LEFT )
panino3 = tk.Label(frame5, text = 'panino3', padx=20)
panino3.pack( side = tk.LEFT )
numeropanini3 =tk.Spinbox(frame5, from_=0, to=10)
numeropanini3.pack( side = tk.RIGHT )
testodescpanino3= "Ingredienti panino 3: ###############,##########,\n #############,##########"
descrizionepanino3 = tk.Label(frame6, text = testodescpanino3)
descrizionepanino3.pack( side = tk.TOP)
#//////////////////////////////////////// PANINO 4
CheckVar4 = tk.IntVar()
radiobutton4= tk.Checkbutton(frame7, variable= CheckVar4, padx=20)
radiobutton4.pack( side = tk.LEFT )
panino4 = tk.Label(frame7, text = 'panino4', padx=10)
panino4.pack( side = tk.LEFT )
numeropanini4 =tk.Spinbox(frame7, from_=0, to=10)
numeropanini4.pack( side = tk.RIGHT )
testodescpanino4= "Ingredienti panino 4: ###############,##########,\n #############,##########"
descrizionepanino4 = tk.Label(frame8, text = testodescpanino4)
descrizionepanino4.pack( side = tk.TOP)
def prezzototale():
stringaqr = ""
i = ""
if CheckVar1.get() == 1:
i = numeropanini1.get()
stringaqr = str(i) + stringaqr + str(panino1.cget("text"))
if CheckVar2.get() == 1:
i = numeropanini2.get()
stringaqr = str(i) + stringaqr + str(panino2.cget("text"))
if CheckVar3.get() == 1:
i = numeropanini3.get()
stringaqr = str(i) + stringaqr + str(panino3.cget("text"))
if CheckVar4.get() == 1:
i = numeropanini4.get()
stringaqr = str(i) + stringaqr + str(panino4.cget("text"))
print(stringaqr)
QRstr = stringaqr
url = pyqrcode.create(QRstr)
url.png('qrordine.png', scale=8)
button = tk.Button(frame9, text = "Pronto!", command = prezzototale())
button.pack( side = tk.TOP )
window.mainloop()
button = tk.Button(frame9, text = "Pronto!", command = prezzototale()) is not correct. The command should have no parenthesis. Try button = tk.Button(frame9, text = "Pronto!", command = prezzototale)
I have got 5 Frames. Frame1 contains the "New Target"-Button. Frame2 and-3 contain a list of Labels. The number of labels depens on how many entries are in the database. Frame4 and -5 contain buttons. Is it possible to add a scrollbar? I tried a lot to add a scrollbar but it doesn´t work.
Here is my code that doesn´t contain the scrollbar:
import tkinter as tk
import mysql.connector
from mysql.connector import Error
from datetime import datetime
import sys
import os
def ende():
main.destroy()
def restart():
main.destroy()
def delete(index):
print(labels[index * 2]["text"])
try:
connection = mysql.connector.connect(host='localhost',
database='databasename',
user='user',
password='password')
cursor = connection.cursor()
sql_Delete_query = """Delete from Targets where Titel = %s"""
cursor.execute(sql_Delete_query, (labels[index * 2]["text"],))
connection.commit()
print("Row deleted successfully ")
except mysql.connector.Error as error:
print("Failed to delete row from table: {}".format(error))
finally:
if (connection.is_connected()):
cursor.close()
connection.close()
print("MySQL connection is closed")
# Restarts the programm
python = sys.executable
os.execl(python, python, *sys.argv)
main = tk.Tk()
# Window size
main.geometry("400x400")
main.resizable(0, 0)
main['bg'] = 'red'
# Window position
w = main.winfo_reqwidth()
h = main.winfo_reqheight()
ws = main.winfo_screenwidth()
hs = main.winfo_screenheight()
x = (ws / 2) - (w / 2)
y = (hs / 2) - (h / 2)
main.geometry('+%d+%d' % (x, y))
fr1 = tk.Frame(main, borderwidth=2, relief="solid", bg="#271ee3", width=400, height=50)
fr2 = tk.Frame(main, borderwidth=2, relief="solid", bg="#0d9467", width=130, height=650)
fr3 = tk.Frame(main, borderwidth=2, relief="solid", bg="#3e1854", width=130, height=650)
fr4 = tk.Frame(main, borderwidth=2, relief="solid", bg="#3e1854", width=70, height=650)
fr5 = tk.Frame(main, borderwidth=2, relief="solid", bg="#3e1854", width=70, height=650)
fr1.pack()
fr2.pack(side="left")
fr3.pack(side="left")
fr4.pack(side="left")
fr5.pack(side="left")
fr2.grid_propagate(False)
fr2.grid_columnconfigure(0, weight=1)
fr3.grid_propagate(False)
fr3.grid_columnconfigure(0, weight=1)
fr4.grid_propagate(False)
fr4.grid_columnconfigure(0, weight=1)
fr5.grid_propagate(False)
fr5.grid_columnconfigure(0, weight=1)
# Button
tb = tk.Button(fr1, text="New Target", width=46, height=2, command=ende)
tb.grid(row=0)
# All targets - empty
labels = []
buttons = []
# Get current date
current_date = datetime.strptime(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), '%Y-%m-%d %H:%M:%S')
# Load all targets
def load_target():
try:
connection = mysql.connector.connect(host='localhost',
database='database',
user='user',
password='password')
sql_select_Query = "select * from Targets"
cursor = connection.cursor()
cursor.execute(sql_select_Query)
records = cursor.fetchall()
print("Total number of rows in ArmbandDB is: ", cursor.rowcount)
i = 0
if cursor.rowcount > 0:
for row in records:
date = current_date - row[2]
labels.append(tk.Label(fr2, text=row[1], pady=15))
labels.append(tk.Label(fr3, text=date, pady=15))
buttons.append(tk.Button(fr4, text="Restart", command=restart, pady=13))
buttons.append(tk.Button(fr5, text="Delete", command=lambda i=i: delete(i), pady=13))
i = i + 1
k = 0
for e in labels:
labels[k].grid(row=k, column=0, sticky='we')
k = k + 1
n = 0
for e in buttons:
buttons[n].grid(row=n, column=0, sticky='we')
n = n + 1
except Error as e:
print("Error reading data from MySQL table", e)
finally:
if (connection.is_connected()):
connection.close()
cursor.close()
print("MySQL connection is closed")
load_target()
print("Anzahl der labels2: ", str(len(labels)))
main.mainloop()
I suppose that the goal of your ScrollBar is to sroll the content of one of your frames.
If so, in tkinter there are no containter like a ScrollArea or ScrollPane in other languages. So you must create it yourself by using a canvas.
from tkinter import *
window = Tk()
frame_container=Frame(window)
canvas_container=Canvas(frame_container, height=100)
frame2=Frame(canvas_container)
myscrollbar=Scrollbar(frame_container,orient="vertical",command=canvas_container.yview) # will be visible if the frame2 is to to big for the canvas
canvas_container.create_window((0,0),window=frame2,anchor='nw')
for i in range(100):
Label(frame2, text=i).pack() # your labels, entries, whatever you whant inside your frame
frame2.update() # update frame2 height so it's no longer 0 ( height is 0 when it has just been created )
canvas_container.configure(yscrollcommand=myscrollbar.set, scrollregion="0 0 0 %s" % frame2.winfo_height()) # the scrollregion mustbe the size of the frame inside it,
#in this case "x=0 y=0 width=0 height=frame2height"
#width 0 because we only scroll verticaly so don't mind about the width.
canvas_container.pack(side=LEFT)
myscrollbar.pack(side=RIGHT, fill = Y)
frame_container.pack()
I have a long chunk of code. I do not want to paste it all here, so let me explain what I am trying to accomplish here. Based on a number provided by the user I want to create that many text boxes and then get what is entered into that text box and insert that into the dictionary. I have tried this a few ways and just cannot get it to work correctly. The list is either empty or it only contains the last text box as the value for each key.
def multiple_choice():
def add():
top.destroy()
top = Tk()
top.title("Add Question")
w = 800
h = 800
ws = top.winfo_screenwidth()
hs = top.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
top.geometry('%dx%d+%d+%d' % (w, h, x, y))
question = Label(top, text="Question to be asked?", font = "Times 14 bold", fg = "blue")
question.grid(row = 2, column = 4)
questionText = Text(top, borderwidth = 5, width=50,height=5, wrap=WORD, background = 'grey')
questionText.grid(row = 3, column = 4)
numQuestions = Label(top, text = "Number of answer choices?", font = "Times 14 bold", fg = "blue")
numQuestions.grid(row = 4, column=4)
num = Entry(top, bd = 5)
num.grid(row=5, column = 4)
answerList = {}
def multiple():
def preview():
preview = Tk()
top.title("Question Preview")
w = 500
h = 500
ws = top.winfo_screenwidth()
hs = top.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
top.geometry('%dx%d+%d+%d' % (w, h, x, y))
title = Label(preview, text = "Short Answer Question Preview", font = "Times 18 bold", fg = "blue" )
title.grid(row = 0, column = 2)
qtext = "Question text will read: "
ques = Label(preview, text = qtext)
ques.grid(row=1, column = 2)
ques2 = Label( preview, text = questionText.get("1.0",END))
let = 'A'
i = 1
for word in answerList:
prev = let + ": " + word
ans = Label(preview, text = prev)
ans.grid(row=1+i, column = 2)
let = chr(ord(let) + 1)
answerCor = "The correct answer(s): "
a = Label(preview, text = answerCor)
a.grid(row=4, column = 2)
b = Label(preview, text = cor.get)
b.grid(row=5, column = 2)
if num.get().isdigit():
number = int(num.get())
AnswerChoices = Label(top, text = "Answer Choices?", font = "Times 14 bold", fg = "blue")
AnswerChoices.grid(row = 6, column=4)
i = 0
let = 'A'
while i < number:
letter = Label(top, text = let)
letter.grid(row = 8+(i*4), column = 3)
answer = Text(top, borderwidth = 5, width=50, height=3, wrap=WORD, background = 'grey')
answer.grid(row = 8+(i*4), column = 4)
answerList[let] = answer.get("1.0",END)
i = i+1
let = chr(ord(let) + 1)
print answerList
correct = Label(top, text = "Correct Answer(s) (seperated by commas)",
font = "Times 14 bold", fg = "blue")
correct.grid(row =99 , column=4)
cor = Text(top, borderwidth = 5, width=50, height=3, wrap=WORD, background = 'grey')
cor.grid(row=100, column = 4)
else:
error = Tk()
w = 500
h = 100
ws = top.winfo_screenwidth()
hs = top.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
error.geometry('%dx%d+%d+%d' % (w, h, x, y))
text = "ERROR: You must enter an integer number"
Label(error,text = text, fg = "red", font = "Times 16 bold").pack()
MyButton5 = Button(top, text="Preview Question", width=20, command = preview, anchor=S)
MyButton5.grid(row=102, column=5)
MyButton4 = Button(top, text="Finish and Add Question", width=20, command = add, anchor=S)
MyButton4.grid(row=102, column=2)
but = Button(top, text="Submit", width=10, command = multiple)
but.grid(row=6, column = 4)
top.mainloop()
def button():
MyButton21 = Button(quiz, text="Short Answer Question", width=20, command = short_answer)
MyButton21.grid(row=8, column=2)
MyButton22 = Button(quiz, text="True/False Question", width=20, command = true_false)
MyButton22.grid(row=8, column=4)
MyButton23 = Button(quiz, text="Multiple Choice Question", width=20, command = multiple_choice)
MyButton23.grid(row=9, column=2)
#MyButton24 = Button(quiz, text="Matching Question", width=20, command = matching)
#MyButton24.grid(row=9, column=4)
MyButton25 = Button(quiz, text="Ordering Question", width=20, command =order)
MyButton25.grid(row=10, column=2)
MyButton26 = Button(quiz, text="Fill in the Blank Question", width=20, command = fill_blank)
MyButton26.grid(row=10, column=4)
MyButton3 = Button(quiz, text="Finsh Quiz", width=10, command = quiz)
MyButton3.grid(row=12, column=3)
quiz = Tk()
w = 700
h = 300
ws = quiz.winfo_screenwidth()
hs = quiz.winfo_screenheight()
x = 0
y = 0
quiz.geometry('%dx%d+%d+%d' % (w, h, x, y))
quiz.title("eCampus Quiz Developer")
L1 = Label(quiz, text="Quiz Title?")
L1.grid(row=0, column=0)
E1 = Entry(quiz, bd = 5)
E1.grid(row=0, column=3)
name_file = E1.get()
name_file = name_file.replace(" ", "")
name_file = name_file + ".txt"
with open(name_file,"w") as data:
MyButton1 = Button(quiz, text="Submit", width=10, command = button)
MyButton1.grid(row=1, column=3)
quiz.mainloop()
I am trying to create the dictionary using this chunk of code:
i = 0
let = 'A'
while i < number:
letter = Label(top, text = let)
letter.grid(row = 8+(i*4), column = 3)
answer = Text(top, borderwidth = 5, width=50, height=3, wrap=WORD, background = 'grey')
answer.grid(row = 8+(i*4), column = 4)
answerList[let] = answer.get("1.0",END)
i = i+1
let = chr(ord(let) + 1)
I have even tried putting a loop in the preview function but that is when the last box was the only value contained in the dictionary. Any ideas would be appreciated
Please see my commeneted snippet below which demonstrates this:
from tkinter import *
class App:
def __init__(self, root):
self.root = root
self.entry = Entry(self.root) #entry to input number of entries later
self.button = Button(self.root, text="ok", command=self.command) #calls command to draw the entry boxes
self.frame = Frame(self.root)
self.entry.pack()
self.button.pack()
self.frame.pack()
def command(self):
self.frame.destroy() #destroys frame and contents
self.frame = Frame(self.root) #recreates frame
self.text = [] #empty array to store entry boxes
for i in range(int(self.entry.get())):
self.text.append(Entry(self.frame, text="Question "+str(i))) #creates entry boxes
self.text[i].pack()
self.done = Button(self.frame, text="Done", command=self.dict) #button to call dictionary entry and print
self.done.pack()
self.frame.pack()
def dict(self):
self.dict = {}
for i in range(len(self.text)):
self.dict.update({self.text[i].cget("text"): self.text[i].get()})
#the above line adds a new dict entry with the text value of the respective entry as the key and the value of the entry as the value
print(self.dict) #prints the dict
root = Tk()
App(root)
root.mainloop()
The above asks the user how many entry widgets they want to create, fills a frame with those entry widgets and then iterates through the list which contains them on the press of a button, adding a new dictionary entry for each entry widget, where the key of the dict is the attribute text for each entry and the value of the dict is the value of each entry.