Checkbutton is not clickable after adding an image to it - python

I started working with tkinter recently and I have the following problem, I need to make the check box bigger but that is only possible with adding an image. The problem is that whenever I add an image to a button it becomes unclickable and the image is not displayed, here is my source code (part of a bigger project). My goal is to display some information and let the user decide which option he gets to keep using the check button. Any help is appreciated.
import tkinter as tk
import tkcalendar as tkc
LARGE_FONT = ("HELVETICA", 32, 'bold')
NORMAL_FONT = ("calibri", 18)
class ConstituireDosar(tk.Toplevel):
def __init__(self, controller):
tk.Toplevel.__init__(self)
self.update_idletasks()
# self.dosar = dosar
self.controller = controller
self.minsize(651, 569)
# self.maxsize(651, 569)
frame_titlu = tk.Frame(self)
frame_titlu.grid(row = 0, column = 0)
frame_continut = tk.Frame(self)
frame_continut.grid(row = 1, column = 0, sticky = "w")
frame_acte = tk.Frame(self)
frame_acte.grid(row = 2, column = 0)
titlu = tk.Label(frame_titlu, font = LARGE_FONT, text = "Constituire Dosar")
titlu.grid(row = 0 , column = 0, padx = 10, pady = 15)
data_emiterii = tk.Label(frame_continut, font = NORMAL_FONT,text = "Data emiterii documentului:")
data_emiterii.grid(row = 1, column = 0, padx = 10, pady = 5, sticky = "w")
self.cal = tkc.DateEntry(frame_continut, date_pattern = "DD/MM/YYYY", width = 20)
self.cal.grid(row = 2, column = 0, padx = 10, pady = 5, sticky = "w")
debitori_label = tk.Label(frame_continut, font = NORMAL_FONT, text = "Selecteaza debitorii.")
debitori_label.grid(row = 3, column = 0, padx = 10, pady = 5, sticky = "w")
debitori = []
tip_debitori = []
for i in range(2):
debitori.append("Person %s " % str(i))
tip_debitori.append("Person %s type" % str(i))
for i in range(len(debitori)):
print(debitori[i])
row_i = 4
self.vars_debitori = []
on_image = tk.PhotoImage(width=48, height=24)
off_image = tk.PhotoImage(width=48, height=24)
on_image.put(("green",), to=(0, 0, 23,23))
off_image.put(("red",), to=(24, 0, 47, 23))
for i in range(len(debitori)):
var = tk.IntVar(frame_continut, value = 0)
interior = debitori[i] + " - " + tip_debitori[i]
# Checkbutton(ws, image=switch_off, selectimage=switch_on, onvalue=1, offvalue=0, variable=cb1, indicatoron=False, command=switchState)
checkbuton = tk.Checkbutton (frame_continut, bd = 5, image = off_image, selectimage = on_image, indicatoron = False, onvalue = 1, offvalue = 0, variable = var, state = tk.ACTIVE, command = lambda: self.toggle(var))
checkbuton.grid(row = row_i, column = 0, padx = 20, pady = 5, sticky = "nw")
checkbuton.image = off_image
# checkbuton.select()
self.vars_debitori.append(var)
row_i += 1
self.vars_acte = []
acte = ["Acte de Procedura", "Incheiere de Admitere", "Cerere de Incuviintare", "Instiintare Creditor"]
for i in range(4):
v = tk.IntVar()
check = tk.Checkbutton(frame_acte, font = NORMAL_FONT, text = acte[i], variable = v)
check.grid(row = row_i, column = 0, padx = 10, pady = 5)
check.select()
self.vars_acte.append(v)
row_i += 1
emite_acte = tk.Button(frame_acte, font = NORMAL_FONT, text = "Emite acte.", command = self.emite_acte)
emite_acte.grid(row = row_i, column = 1, padx = 15, pady = 30, ipadx = 70, ipady = 10)
emite_acte.configure(bg = '#218838', fg = '#FFFFFF')
buton_cancel = tk.Button(frame_acte, font = NORMAL_FONT, text = "Cancel", command = lambda: self.destroy())
buton_cancel.grid(row = row_i, column = 0, padx = 15, pady = 30, ipadx = 70, ipady = 10)
buton_cancel.configure(bg = "red", fg = '#FFFFFF')
def emite_acte(self):
print(self.cal.get_date().strftime("%d/%m/%y"))
print(self.winfo_height(), self.winfo_width())
if __name__ == "__main__":
root = tk.Tk()
app = ConstituireDosar(root)
app.protocol("WM_DELETE_WINDOW", root.destroy)
root.withdraw()
root.mainloop()
I tried some options that I saw on the forum, in another file they worked fine but when I tried to implement it in the project itself the checkbutton is still unclickable and it doesn't display the images either. tkinter checkbutton different image I tried to replicate Bryan's answer, but no luck there. Also didn't receive any console error message.

As #furas pointed in the comments above, the problem got fixed with keeping the images as member variables of the class, also the button became clickable after removing the self.toggle(var) command from checkbutton

Related

Tkinter: How to prevent contents from previous searches appearing on a forthcoming search

currently working on an API-based F1 drivers' app using Python and Tkinter.
The issue I'm facing is that contents from previous searches appear on forthcoming content.
Visually, the issue can be best represented here, where the new content appears on top of the old content, which is no good.
To solve this problem, I know that logically, there should be some approach where when user presses search_button, the button should be attempting to clear the previous search's content in main_frame and then recreate main_frame with the new content.
Generally, it's not too difficult to clear content in a frame, since that's through using w_info and the .destroy() method, but I don't know how to recreate a frame with new content. In other words, I'm having trouble programming out the logic (perhaps the logic should be clearer or there should be different logic)
Here's the code:
#Go to
from tkinter import *
from tkinter import ttk
from PIL import ImageTk, Image
from tkinter import messagebox
import requests
import json
root = Tk()
root.geometry("800x300")
root.title("F1 Desktop Application")
root.iconbitmap("formula1_logo.ico")
#generate 2022 drivers-list [can scale to drivers-list by changing the]
drivers_list_request = requests.get("http://ergast.com/api/f1/2022/drivers.json")
#initialize empty-list
drivers_list = []
drivers_list_object = json.loads(drivers_list_request.content)
for elements in drivers_list_object["MRData"]["DriverTable"]["Drivers"]:
drivers_list.append(elements["givenName"] + " " + elements["familyName"])
# Update the Entry widget with the selected item in list
def check(e):
v= entry_box.get()
if v=='':
hide_button(menu)
else:
data=[]
for item in drivers_list:
if v.lower() in item.lower():
data.append(item)
update(data)
show_button(menu)
def update(data):
# Clear the Combobox
menu.delete(0, END)
# Add values to the combobox
for value in data:
menu.insert(END,value)
def fillout(event):
try:
entry_box.delete(0,END)
entry_box.insert(0,menu.get(menu.curselection()))
hide_button(menu)
#handle a complete deletion of entry-box via cursor double tap
except:
pass
def hide_button(widget):
widget.grid_remove()
def show_button(widget):
widget.grid()
def full_name():
lower_user_input = grab_user_input()
response = requests.get("http://ergast.com/api/f1/drivers/{}.json".format(lower_user_input))
response_object = json.loads(response.content)
name = response_object["MRData"]["DriverTable"]["Drivers"][0]["givenName"] + " " + response_object["MRData"]["DriverTable"]["Drivers"][0]["familyName"]
driver_name_label.configure(text = name)
def team():
lower_user_input = grab_user_input()
response = requests.get("http://ergast.com/api/f1/current/drivers/{}/constructors.json".format(lower_user_input))
response_object = json.loads(response.content)
team = response_object["MRData"]["ConstructorTable"]["Constructors"][0]["name"]
team_api = Label(main_frame, text = team, font = ("Arial", 10))
team_api.grid(row = 1, column = 1)
def driver_code():
lower_user_input = grab_user_input()
response = requests.get("http://ergast.com/api/f1/drivers/{}.json".format(lower_user_input))
response_object = json.loads(response.content)
code = response_object["MRData"]["DriverTable"]["Drivers"][0]["code"]
code_api = Label(main_frame, text = code, font = ("Arial", 10))
code_api.grid(row = 3, column = 1, sticky = W)
def nationality():
lower_user_input = grab_user_input()
response = requests.get("http://ergast.com/api/f1/drivers/{}.json".format(lower_user_input))
response_object = json.loads(response.content)
nationality = response_object["MRData"]["DriverTable"]["Drivers"][0]["nationality"]
nationality_api = Label(main_frame, text = nationality, font = ("Arial", 10))
nationality_api.grid(row = 2, column = 1, sticky = W)
def wins():
lower_user_input = grab_user_input()
response = requests.get("http://ergast.com/api/f1/drivers/{}/results/1.json".format(lower_user_input))
response_object = json.loads(response.content)
wins = response_object["MRData"]["total"]
wins_api = Label(main_frame, text = wins, font = ("Arial", 10))
wins_api.grid(row = 4, column = 1, sticky = W)
def poles():
lower_user_input = grab_user_input()
response = requests.get("http://ergast.com/api/f1/drivers/{}/qualifying/1.json".format(lower_user_input))
response_object = json.loads(response.content)
poles = response_object["MRData"]["total"]
poles_api = Label(main_frame, text = poles, font = ("Arial", 10))
poles_api.grid(row = 2, column = 3, sticky = W, padx = 15)
def podiums():
lower_user_input = grab_user_input()
#podiums is sum of 1st, 2nd, 3rd place finishes
#####DRY principle; let's reuse the code from wins()
######noticing how maybe should create a separate function which "places" the widget
#######for now, reuse the code
#1st place finishes
response = requests.get("http://ergast.com/api/f1/drivers/{}/results/1.json".format(lower_user_input))
response_object = json.loads(response.content)
#convert wins to int
wins = int(response_object["MRData"]["total"])
#2nd place finishes
response_ii = requests.get("http://ergast.com/api/f1/drivers/{}/results/2.json".format(lower_user_input))
response_ii_object = json.loads(response_ii.content)
response_ii_amount = int(response_ii_object["MRData"]["total"])
#3rd place finishes
response_iii = requests.get("http://ergast.com/api/f1/drivers/{}/results/3.json".format(lower_user_input))
response_iii_object = json.loads(response_iii.content)
response_iii_amount = int(response_iii_object["MRData"]["total"])
podiums = str(wins + response_ii_amount + response_iii_amount)
podiums_api = Label(main_frame, text = podiums, font = ("Arial", 10))
podiums_api.grid(row = 1, column = 3, padx = 15, sticky = W)
def championships():
lower_user_input = grab_user_input()
response = requests.get("http://ergast.com/api/f1/drivers/{}/driverStandings/1/seasons.json".format(lower_user_input))
response_object = json.loads(response.content)
championships = response_object["MRData"]["total"]
championships_api = Label(main_frame, text = championships, font = ("Arial", 10))
championships_api.grid(row = 3, column = 3, padx = 15, sticky = W)
def standing():
lower_user_input = grab_user_input()
response = requests.get("http://ergast.com/api/f1/current/drivers/{}/driverStandings.json".format(lower_user_input))
response_object = json.loads(response.content)
position = response_object["MRData"]["StandingsTable"]["StandingsLists"][0]["DriverStandings"][0]["position"]
points = response_object["MRData"]["StandingsTable"]["StandingsLists"][0]["DriverStandings"][0]["points"]
standing = "{} ({} pts)".format(position, points)
standing_api = Label(main_frame, text = standing, font = ("Arial", 10))
standing_api.grid(row = 4, column = 3, padx = 15, sticky = W)
def grab_user_input():
user_input = entry_box.get()
lower_user_input = user_input.lower().split(" ")[1]
return lower_user_input
def search():
#slow run-time is simply due to the multiple api calls made
#perhaps less-so due to not completely following DRY principles
full_name()
team()
driver_code()
nationality()
wins()
poles()
podiums()
championships()
standing()
show_button(main_frame)
left_frame = LabelFrame(root, width = 275, height = 300)
left_frame.grid(row = 1, column = 0, sticky = SE)
left_frame.grid_propagate(False)
search_label = Label(left_frame, text = "Search Driver", font = ("Arial bold", 12))
search_label.grid(row = 0, column = 0, pady = 10)
entry_box = Entry(left_frame, bd = 5)
entry_box.grid(row = 1, column = 0, padx = 35, pady = 40)
entry_box.bind('<KeyRelease>',check)
search_button = Button(left_frame, text = "search", command = search)
search_button.grid(row = 1, column = 1, padx = 15)
menu= Listbox(left_frame, height = 7)
menu.grid(row = 2, column = 0)
menu.bind("<<ListboxSelect>>",fillout)
main_frame = LabelFrame(root, width = 575, height = 300)
main_frame.grid(row = 1, column = 1, sticky = SE)
main_frame.grid_propagate(False)
driver_name_label = Label(main_frame, text = "Driver", font = ("Arial", 15))
driver_name_label.grid(row = 0, column = 0,pady = 30)
team_label = Label(main_frame, text = "TEAM", font = ("Arial", 10))
team_label.grid(row = 1, column = 0, sticky = W)
nationality_label = Label(main_frame, text = "NATIONALITY", font = ("Arial", 10))
nationality_label.grid(row = 2, column = 0, sticky = W)
driver_code_label = Label(main_frame, text = "DRIVER CODE", font = ("Arial", 10))
driver_code_label.grid(row = 3, column = 0, sticky = W)
wins_label = Label(main_frame, text = "WINS", font = ("Arial", 10))
wins_label.grid(row = 4, column = 0, sticky = W)
podiums_label = Label(main_frame, text = "PODIUMS", font = ("Arial", 10))
podiums_label.grid(row = 1, column = 2, sticky = W, padx = 15)
poles_label = Label(main_frame, text = "POLES", font = ("Arial", 10))
poles_label.grid(row = 2, column = 2, sticky = W, padx = 15)
world_championships_label = Label(main_frame, text = "WORLD CHAMPIONSHIPS", font = ("Arial", 10))
world_championships_label.grid(row = 3, column = 2, padx = 15, sticky = W)
current_standing_label = Label(main_frame, text = "F1 2022 STANDING", font = ("Arial", 10))
current_standing_label.grid(row = 4, column = 2, padx = 15, sticky = W)
hide_button(menu)
hide_button(main_frame)
root.mainloop()
Would appreciate the help! If there are any follow-up questions for clarity, let me know!
Thanks, Safwan

Adding a tkcalendar DateEntry to a tkinter GUI

this my situation. I'm learning how to use python (I just started) to create a GUI with Tkinter. One requirement of my application is to be able to store "DateEntry", while investigating I came across with tkcalendar DateEntry. The problem is that DateEntry is created as a class but my already created window(GUI) is a class as well and I don't know how to combine the class DateEntry into my class client which creates a mainwindow, I think that's beyond my knowledge. I want a DateEntry to be displayed in another toplevel() window when the button "Fecha Check-in" is used. Can anyone explain how to do it?
this is the image
This is the code:
from tkcalendar import DateEntry
from datetime import date
from tkinter import ttk
from tkinter import *
import sqlite3
#year = datetime.date.today().year
#month = datetime.date.today().month
class client:
def __init__(self, window):
self.wind = window
self.wind.title('Start Bits CheckIn-CheckOut')
#self.wind.columnconfigure(0, weight = 1)
#self.wind.rowconfigure(0, weight = 1)
#self.wind.geometry("330x300")
frame_2 = Label(self.wind, text = 'Registro de huéspedes')
frame_2.grid(row = 0, column = 0, pady = 5)
#
frame = LabelFrame(self.wind, text = 'Datos personales', borderwidth=4, relief="raised")
frame.grid(row = 1, column = 0, columnspan = 10, pady = 2, sticky = W + E)
#
# #label ID
L_ID = Label(frame, text = 'Cédula: ').grid(row = 1, column = 0, padx = 1, pady = 1)
self.ID = Entry(frame, width = 25)
self.ID.focus()
self.ID.grid(row = 1, column = 1, columnspan = 2)
#label Nombre
L_name = Label(frame, text = 'Nombres: ').grid(row = 2, column =0, padx = 1, pady = 2)
self.nombre = Entry(frame, width = 25)
self.nombre.grid(row = 2, column = 1, columnspan = 2)
#label last
L_last = Label(frame, text = 'Apellidos: ').grid(row = 3, column = 0, padx = 1, pady = 2)
self.last = Entry(frame, width = 25)
self.last.grid(row = 3, column = 1, columnspan = 2)
#label contact phone
L_phone = Label(frame, text = 'Teléfono: ').grid(row = 4, column = 0, padx = 1, pady = 2)
self.phone = Entry(frame, width = 25)
self.phone.grid(row = 4, column = 1, columnspan = 2)
#label email
L_mail = Label(frame, text = 'Email: ').grid(row = 5, column = 0, padx = 1, pady = 2)
self.mail = Entry(frame, width = 25)
self.mail.grid(row = 5, column = 1, columnspan = 2)
#label CheckIn
L_ChkIN = Label(frame, text = 'Check-In: ').grid(row = 6, column = 0, padx = 1, pady = 5)
ttk.Button(frame, text = 'Fecha Check-In', command = self.fecha_In).grid(row = 6, column = 2)
#label CheckOut
L_ChkOut = Label(frame, text = 'Check-Out').grid(row = 7, column = 0, padx = 1, pady = 5)
#button registrar
ttk.Button(frame, text = 'Registrar' ).grid(row = 2, column = 6, padx = 10)
#button actualizar
ttk.Button(frame, text = 'Actualizar').grid(row = 4, column = 6, padx = 10)
def fecha_In(self):
self.fecha_in = Toplevel()
self.fecha_in.title = 'Fecha Check-In'
if __name__ == '__main__':
window = Tk()
style = ttk.Style(window)
style.theme_use('clam')
alien = PhotoImage(file = "Start Bits.png")
fondo = Label(window, image = alien).grid(row = 8, column = 0)
application = client(window)
window.mainloop()

How to change the state of a canvas

I was wondering how I could hide my canvas from the user and then make it reappear when I want it to. I tried using canvas.config(state = "disabled") but it doesn't hide it. When I try canvas.config(state = "hidden") it will say I have to use normal or disabled. Here is the code:
from tkinter import *
from tkinter import ttk
root = Tk()
def redCallback():
labelRed = ttk.Label(frameTwo, text = "Red", background = "red")
labelRed.grid(row = 1, column = 0, pady = 5, ipadx = 35, ipady = 5)
def orangeCallback():
labelOrange = ttk.Label(frameTwo, text = "Orange", background = "orange")
labelOrange.grid(row = 1, column = 1, pady = 5, ipadx = 25, ipady = 5)
def yellowCallback():
labelYellow = ttk.Label(frameTwo, text = "Yellow", background = "yellow")
labelYellow.grid(row = 1, column = 2, pady = 5, ipadx = 26, ipady = 5)
def greenCallback():
labelGreen = ttk.Label(frameTwo, text = "Green", background = "green")
labelGreen.grid(row = 1, column = 3, pady = 5, ipadx = 30, ipady = 5)
def blueCallback():
labelBlue = ttk.Label(frameTwo, text = "Blue", background = "blue")
labelBlue.grid(row = 1, column = 4, pady = 5, ipadx = 33, ipady = 5)
def return_press(event):
labelCanvas = ttk.Label(frameThree, text = "Now draw on the canvas!")
labelCanvas.pack()
def mouse_press(event):
global prev
print('type: {}'.format(event.type))
print('widget: {}'.format(event.widget))
print('num: {}'.format(event.num))
print('x: {}'.format(event.x))
print('y: {}'.format(event.y))
print('x_root: {}'.format(event.x_root))
print('y_root: {}\n'.format(event.y_root))
prev = event
def draw(event):
global prev
canvas.create_line(prev.x, prev.y, event.x, event.y, width = 5)
prev = event
frameOne = ttk.Frame(root)
frameOne.pack()
frameTwo = ttk.Frame(root)
frameTwo.pack()
frameThree = ttk.Frame(root)
frameThree.pack()
labelPallet = ttk.Label(frameOne, text = "Click the buttons below, and then tap ENTER")
labelPallet.pack()
buttonRed = ttk.Button(frameTwo, text = "Red", command = redCallback)
buttonRed.grid(row = 0, column = 0, ipadx = 10, ipady = 5)
buttonOrange = ttk.Button(frameTwo, text = "Orange", command = orangeCallback)
buttonOrange.grid(row = 0, column = 1, ipadx = 10, ipady = 5)
buttonYellow = ttk.Button(frameTwo, text = "Yellow", command = yellowCallback)
buttonYellow.grid(row = 0, column = 2, ipadx = 10, ipady = 5)
buttonGreen = ttk.Button(frameTwo, text = "Green", command = greenCallback)
buttonGreen.grid(row = 0, column = 3, ipadx = 10, ipady = 5)
buttonBlue = ttk.Button(frameTwo, text = "Blue", command = blueCallback)
buttonBlue.grid(row = 0, column = 4, ipadx = 10, ipady = 5)
canvas = Canvas(root, width = 640, height = 480, background = "white")
canvas.pack()
root.bind("<Return>", return_press)
canvas.bind('<ButtonPress>', mouse_press)
canvas.bind("<B1-Motion>", draw)
Currently the program just has buttons, that when clicked, will create labels in that colour. I want the canvas to be hidden until the labelCanvas is printed.

tkinter window is blank after executing code

I'm starting to code with Python and on my first application I have reached a brick wall. Any help on why this code is not displaying the widgets will be greatly appreciated!
import tkinter
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
class ImprintPlusApp:
def _init_(self, master):
self.frame_header = ttk.Frame(master)
self.frame_header.pack()
ttk.Label(self.header_frame, text = "Bienvenidos a Imprint Plus Manager")
self.frame_crearorden = ttk.Frame(master)
self.frame_crearorden.pack()
ttk.Label(self.frame_crearorden, text = "Nombre").grid(row = 0, column = 0, padx = 5)
ttk.Label(self.frame_crearorden, text = "Email").grid(row = 2, column = 0, padx = 5)
ttk.Label(self.frame_crearorden, text = "Numero Cel/Tel").grid(row = 4, column = 0, padx = 5)
ttk.Label(self.frame_crearorden, text = "Información Adicional").grid(row = 6, column = 0, padx = 5)
self.entry_name = ttk.Entry(self.frame_crearorden, width = 24)
self.entry_email = ttk.Entry(self.frame_crearorden, width = 24)
self.entry_numtc = ttk.Entry(self.frame_crearorden, width = 24)
self.entry_addinf = Text(self.frame_crearorden, width = 50, height = 10)
self.entry_name.grid(row = 0, column = 1, padx = 5)
self.entry_email.grid(row = 2, column = 1, padx = 5)
self.entry_numtc.grid(row = 4, column = 1, padx = 5)
self.entry_addinf.grid(row = 7, column = 0, columnspan = 2, padx = 5)
ttk.Button(self.frame_crearorden, text = "Submit", command = self.submit).grid(row = 8, columnspan = 1, padx = 5)
ttk.Button(self.frame_crearorden, text = "Clear", command = self.clear).grid(row = 8, columnspan = 0, padx = 5)
def submit(self):
print ("Nombre: {}".format(self.entry_name.get()))
print ("Email: {}".format(self.entry_name.get()))
print ("Num Cel/Tel: {}".format(self.entry_name.get()))
print ("Información Adicional: {}".format(self.entry_name.get(1.0, "end")))
self.clear()
messagebox.showinfo(tite = "Orden #", message = "Orden Guardada")
def clear(self):
self.entry_name.delete(0, "end")
self.entry_email.delete(0, "end")
self.entry_numtc.delete(0, "end")
self.entry_addinf.delete(1.0, "end")
def main():
root = Tk()
app = ImprintPlusApp()
root.mainloop()
if __name__ == '__main__':
main()
Everytime I launch the code I get a blank tkinter window.
This had a few problems.
You had an _init_ method, not an __init__ method, so the created object wasn't being initialized.
You have to send the root tkinter object to the application, with app = ImprintPlusApp(root).
You had a self.header_frame once instead of self.frame_header.
You had a columnspan = 0 (which is invalid) instead of columnspan = 1 (which doesn't really need to be specified).
I've made the above changes in the code below. It may still need debugging, as I don't know exactly what design you had in mind.
import tkinter
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
class ImprintPlusApp:
def __init__(self, master):
self.frame_header = ttk.Frame(master)
self.frame_header.pack()
ttk.Label(self.frame_header, text = "Bienvenidos a Imprint Plus Manager")
self.frame_crearorden = ttk.Frame(master)
self.frame_crearorden.pack()
ttk.Label(self.frame_crearorden, text = "Nombre").grid(row = 0, column = 0, padx = 5)
ttk.Label(self.frame_crearorden, text = "Email").grid(row = 2, column = 0, padx = 5)
ttk.Label(self.frame_crearorden, text = "Numero Cel/Tel").grid(row = 4, column = 0, padx = 5)
ttk.Label(self.frame_crearorden, text = "Información Adicional").grid(row = 6, column = 0, padx = 5)
self.entry_name = ttk.Entry(self.frame_crearorden, width = 24)
self.entry_email = ttk.Entry(self.frame_crearorden, width = 24)
self.entry_numtc = ttk.Entry(self.frame_crearorden, width = 24)
self.entry_addinf = Text(self.frame_crearorden, width = 50, height = 10)
self.entry_name.grid(row = 0, column = 1, padx = 5)
self.entry_email.grid(row = 2, column = 1, padx = 5)
self.entry_numtc.grid(row = 4, column = 1, padx = 5)
self.entry_addinf.grid(row = 7, column = 0, columnspan = 2, padx = 5)
ttk.Button(self.frame_crearorden, text = "Submit", command = self.submit).grid(row = 8, columnspan = 1, padx = 5)
ttk.Button(self.frame_crearorden, text = "Clear", command = self.clear).grid(row = 8, columnspan = 1, padx = 5)
def submit(self):
print ("Nombre: {}".format(self.entry_name.get()))
print ("Email: {}".format(self.entry_name.get()))
print ("Num Cel/Tel: {}".format(self.entry_name.get()))
print ("Información Adicional: {}".format(self.entry_name.get(1.0, "end")))
self.clear()
messagebox.showinfo(tite = "Orden #", message = "Orden Guardada")
def clear(self):
self.entry_name.delete(0, "end")
self.entry_email.delete(0, "end")
self.entry_numtc.delete(0, "end")
self.entry_addinf.delete(1.0, "end")
def main():
root = Tk()
app = ImprintPlusApp(root)
root.mainloop()
if __name__ == '__main__':
main()

create a mathematis matrix with python

Well, I've looked a lot in the web before asking, so here's the thing.
I'm not really experienced in Python and I need to develop this Matrix Generator. Yes, it is a mathematics matrix. I'm using Tkinter and Python 3.3.
First i ask the Number of Rows and Columns and then I fill each field and the code transforms it in a notepad for other programs to read.
I used the grid method so i'm having trouble with large scale matrices. The thing is I need to apply a scrollbar. I have read that I can use frame and a friend of mine showed me a scrollbar he made using frames. Can you help me? ;D
Every time I refer to linhas is the same as rows and colunas is the same as columns.
import tkinter
class DropDown:
def __init__(self):
self._list_window = tkinter.Tk();
self._row_var = tkinter.StringVar(self._list_window)
self._col_var = tkinter.StringVar(self._list_window)
self._row_var.set(0)
self._col_var.set(0)
self._rows = None
self._columns = None
self._row_label = tkinter.Label(
master = self._list_window,
text = 'Number of rows: ')
self._row_label.grid(
row = 0, column = 0, padx = 5, pady = 5,
sticky = tkinter.NE)
self._row_entry = tkinter.Entry(self._list_window, width=1)
self._row_entry.grid(
row = 0, column = 1, padx = 5, pady = 5,
sticky = tkinter.EW)
self._column_label = tkinter.Label(
master = self._list_window,
text = 'Number of columns: ')
self._column_label.grid(
row = 1, column = 0, padx = 5, pady = 5,
sticky = tkinter.NE)
self._column_entry = tkinter.Entry(self._list_window)
self._column_entry.grid(
row = 1, column = 1, padx = 5, pady = 5,
sticky = tkinter.EW)
self._list_window.columnconfigure(1, weight = 1)
self._OK_button = tkinter.Button(
master = self._list_window, text = "OK",
command = self.get_dimensions)
self._OK_button.grid(
row = 2, column = 0, columnspan = 2,
padx = 5, pady = 5)
def get_dimensions(self):
self._rows = self._row_entry.get()
self._columns = self._column_entry.get()
self._list_window.destroy()
def show(self):
self._list_window.mainloop()
if self._rows != None and self._columns != None:
return (int(self._rows), int(self._columns))
else:
return (None, None)
class matrix:
def __init__(self, linhas, colunas):
self.linhas=linhas
self.colunas=colunas
self.mwindow=tkinter.Tk()
self.vars = [[] for x in range(self.linhas) ]
for i in range(self.linhas):
for j in range(self.colunas):
v=tkinter.StringVar()
self.vars[i].append(v)
entry = tkinter.Entry(master = self.mwindow, textvariable = self.vars[i][j])
entry.grid(row = i, column = j, padx = 10, pady = 10)
self.botOK=tkinter.Button(master=self.mwindow, text="OK", command=self.OK)
self.botOK.grid(row=self.linhas+1, column=(self.colunas//2)-1, columnspan=2, padx=5, pady=5)
def Start(self):
self.mwindow.mainloop()
return self.lista
def OK(self):
self.lista = []
for i in range(self.linhas):
for j in range(self.colunas):
self.lista.append(self.vars[i][j].get())
self.mwindow.destroy()
dimensoes= DropDown().show()
#print (dimensoes)
if dimensoes[0]<dimensoes[1]:
diag=dimensoes[0]
else:
diag=dimensoes[1]
matriz=matrix(dimensoes[0], dimensoes[1]).Start()
with (open("notepadmatrix.txt", "w")) as arquivo:
arquivo.write(str(dimensoes[0]*dimensoes[1])+"\n")
arquivo.write(str(dimensoes[0])+"\n")
arquivo.write(str(dimensoes[1])+"\n")
arquivo.write(str(diag)+"\n")
for i in matriz:
arquivo.write(i+"\n")
arquivo.write("fim")
and here goes the code he gave me to the scroll bar.
class Earnings():
def __init__(self, Ticker, EPS, Time):
self._root_window = tkinter.Tk()
self.canvas = tkinter.Canvas(master = self._root_window, background = '#8989E0')
self.canvas.config(scrollregion=[0,0,600,10000])
self.frame = tkinter.Frame(master = self.canvas)
self.scrollbar = tkinter.Scrollbar(master = self._root_window, orient = tkinter.VERTICAL)
self.frame.pack(side = tkinter.LEFT, fill = tkinter.BOTH, expand = tkinter.TRUE)
self.canvas.create_window((0,0), window=self.frame, anchor=tkinter.NW)
self.scrollbar.pack(side = tkinter.RIGHT, fill = tkinter.BOTH, expand = tkinter.TRUE)
self.canvas.pack(side = tkinter.TOP, fill = tkinter.BOTH, expand = tkinter.TRUE)
self.scrollbar.config(command = self.canvas.yview)
self.canvas.config(yscrollcommand = self.scrollbar.set)
self.ticker = Ticker
self.EPS = EPS
self.time = Time
for i in range(len(self.ticker)):
self.TickerButton = tkinter.Button(
master = self.frame,
text = self.ticker[i],
command = lambda i=i: self.search_ticker(self.ticker[i]))
self.TickerButton.grid(row = i+1, column = 0, padx = 10, pady = 10,
sticky = tkinter.W)
self.EPSLabel = tkinter.Label(
master = self.frame,
text = self.EPS[i])
self.EPSLabel.grid(row = i+1, column = 1, padx = 10, pady = 10,
sticky = tkinter.W)
self.TimeLabel = tkinter.Label(
master = self.frame,
text = self.time[i])
self.TimeLabel.grid(row = i+1, column = 2, padx = 10, pady = 10,
sticky = tkinter.W)
TkInter is long in the tooth, I'd use Kivy Grid layout instead:
http://kivy.org/docs/api-kivy.uix.gridlayout.html?highlight=grid

Categories