Centered text in Tkinter GRID - python

I have a problem with grid manager in Python Tkinter.
I was add a Frame and labels inside it appeared in center instead of left top.
What is the problem with my code?
Thanks.
GUIImage
from tkinter import *
class PacijentGUI(Tk):
def __init__(self):
super().__init__()
self.napraviGUI()
def napraviGUI(self):
#Listbox
self.__pacijentiListbox = Listbox(self,width=35, height=15)
self.__pacijentiListbox.grid(row=0,column = 0,sticky = E)
#Frame
panelZaPrikaz = Frame(self, borderwidth = 2, relief = "ridge", padx=100,pady = 78)
panelZaPrikaz.grid(row=0,column = 1,sticky = E)
#Labels in frame
Label(panelZaPrikaz,text = "LBO: ").grid(row = 0,column = 0)
Label(panelZaPrikaz,text = "Ime: ").grid(row = 1,column = 0)
Label(panelZaPrikaz,text="Prezime: ").grid(row = 2,column = 0)
Label(panelZaPrikaz,text = "Datum rodjenja: ").grid(row = 3,column=0)
def main():
app = PacijentGUI()
app.geometry("800x600")
app.title('Evidencija')
app.mainloop()
if __name__ == '__main__':
main()

Related

Getting error when trying to create tkinter frame?

I'm trying to understand the following example below:
import sys
from tkinter import *
def btn():
login_frame.destroy()
home_frame = home()
home_frame.pack(fill="both", expand=True)
def btn2():
home_frame.destroy()
#home_frame = home()
#home_frame.pack(fill="both", expand=True)
def login():
frame = Frame(root)
Label(frame, text = "test1").grid(row = 0)
Label(frame, text = "test2").grid(row = 1)
Label(frame, text = "test3").grid(row = 2)
e1 = Entry(frame)
e2 = Entry(frame)
e1.grid(row=1, column = 1)
e2.grid(row=2, column = 1)
Button(frame, text = 'btn1', command = btn).grid(row = 4, column = 0, sticky = W, pady = 4)
Button(frame, text = 'btn2', command = btn).grid(row = 4, column = 1, sticky = W, pady = 4)
return frame
def home():
frame = Frame(root)
Label(frame, text="Welcome").pack()
Button(frame, text = 'test', command = btn2).pack()
return frame
root = Tk()
root.wm_title('test')
login_frame = login()
login_frame.pack(fill="both", expand=True)
root.mainloop()
I create the first login_frame, and btn1 destroys it and creates home_frame right? but when I click the next btn I get the following error:
NameError: name 'home_frame' is not defined
Why isn't this frame defined? I thought it would have been defined when btn is pushed and home_frame = home() ?

Radio Buttons tkinter python

I have an issue where all my radio buttons are selected when I try to click one of them. It is for a conversion calculator, so once I solve this issue I will be able to carry the same code over for my other conversions. Any help is greatly appreciated.
Thanks,
Jamie
`from tkinter import*
from tkinter import ttk
class GUI:
def __init__(self, root):
notebook = ttk.Notebook(root)
notebook.pack()
self.temp_frame = ttk.Frame(notebook)
self.length_frame = ttk.Frame(notebook)
self.weight_frame = ttk.Frame(notebook)
#-----------------Length------------------------#
notebook.add(self.length_frame, text = "Length")
#Radio Buttons
v = StringVar()
MODES = ["mm","cm","Inch","Feet","Yards","Metre","Km","Miles"]
v.set("0") # initialize
r=0
for r in range(len(MODES)):
b = ttk.Radiobutton(self.length_frame, text=MODES[r], variable=v )
b.grid(row=r ,column = 0, sticky = W)
#Radio Buttons
v1 = StringVar()
MODES1 = ["mm","cm","Inch","Feet","Yards","Metre","Km","Miles"]
v1.set("0")#initialize
r=0
for r in range(len(MODES1)):
b = ttk.Radiobutton(self.length_frame, text=MODES1[r], variable=v1 )
b.grid(row=r ,column = 6, sticky = W)
#Entry Box
self.Text_length_left = StringVar()
self.entry_length_left = ttk.Entry(self.length_frame, textvariable = self.Text_length_left, width = 15)
self.entry_length_left.grid(row = 4, column = 2)
self.Text_length_right = StringVar()
self.entry_length_right = ttk.Entry(self.length_frame, textvariable = self.Text_length_right, width = 15, state = "readonly")
self.entry_length_right.grid(row = 4, column = 4)
#Label
self.label_3 = Label(self.length_frame, text = "From:")
self.label_3.grid(row = 3, column = 2)
self.label_4 = Label(self.length_frame, text = "To:")
self.label_4.grid(row = 3, column = 4)
self.label_1 = Label(self.length_frame, text = "-->")
self.label_1.grid(row = 4, column = 3)
self.label_2 = Label(self.length_frame, text = " ")
self.label_2.grid(row = 4, column = 5)
#---------------------Temp Frame ----------------------#
notebook.add(self.temp_frame, text = "Temperature")
if __name__ == "__main__":
root = Tk()
app = GUI(root)
root.mainloop()`
You never set the value keyword. This is what's stored in the control variable for a group of radiobuttons when clicked.

Tkinter, canvas unable to scroll

I'm trying to make a Tkinter window class that contains a canvas with a scrollbar based on the tkinter Toplevel class. When I run my code I don't receive any errors but the scrollbar in the window is disabled. The Frame or canvas that has the information wont stretch with the window when I stretch it manually after the program is running. Here is the bugged code:
class new_window(Toplevel):
def __init__(self,master):
Toplevel.__init__(self,master)
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
s = Scrollbar(self, orient = VERTICAL)
s.grid(row = 0, column = 1, sticky = NS)
self.can = Canvas(self, yscrollcommand=s.set)
self.can.grid(row = 0, column = 0, sticky = N+S+E+W)
self.win = Frame(self.can)
self.can.create_window(0,0, window = self.win, anchor = NW)
s.config(command = self.can.yview)
size = (self.win.winfo_reqwidth(), self.win.winfo_reqheight())
self.can.config(scrollregion="0 0 %s %s" % size)
self.win.update_idletasks()
self.ca.configure(scrollregion = (1,1,win.winfo_width(),win.winfo_height()))
def create(self):
for i in range (100):
i = Label(self.win, text = str(i))
i.grid()
root = Tk()
win = new_window(root)
win.create()
root.mainloop()
It was working fine before I decided to implement classes:
from Tkinter import *
root = Tk()
window = Toplevel()
window.grid_rowconfigure(0, weight=1)
window.grid_columnconfigure(0, weight=1)
s = Scrollbar(window, orient = VERTICAL)
s.grid(row = 6, column = 1, sticky = NS)
can = Canvas(window, width = 1600, height = 700, yscrollcommand=s.set)
can.grid(row = 6, column = 0, sticky = NSEW)
win = Frame(can)
can.create_window(0,0, window = win, anchor = NW)
s.config(command = can.yview)
for i in range(100):
lbl = Label(win, text = str(i))
lbl.grid()
win.update_idletasks()
can.configure(scrollregion = (1,1,win.winfo_width(),win.winfo_height()))
root.mainloop()
Im not sure where I went wrong in the transition, any help would be greatly appreciated.
I think the issue is coming from here:
self.win.update_idletasks()
self.ca.configure(scrollregion = (1,1,win.winfo_width(),win.winfo_height()))
This is inside the initialization function, when it should be updating after the create function is called. There's still probably a more efficient way to structure this, but this should work in the meantime:
from Tkinter import *
class new_window(Toplevel):
def __init__(self,master):
Toplevel.__init__(self,master)
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
s = Scrollbar(self, orient = VERTICAL)
s.grid(row = 0, column = 1, sticky = NS)
self.can = Canvas(self, yscrollcommand=s.set)
self.can.grid(row = 0, column = 0, sticky = N+S+E+W)
self.win = Frame(self.can)
self.can.create_window(0,0, window = self.win, anchor = NW)
s.config(command = self.can.yview)
size = (self.win.winfo_reqwidth(), self.win.winfo_reqheight())
self.can.config(scrollregion="0 0 %s %s" % size)
def create(self):
for i in range (100):
i = Label(self.win, text = str(i))
i.grid()
self.win.update_idletasks()
self.can.configure(scrollregion = (1,1,self.win.winfo_width(),self.win.winfo_height()))
root = Tk()
win = new_window(root)
win.create()
root.mainloop()

TKinter math output to canvas.create_text

I am trying to calculate a formula and display its output as a table in TKinter. Since it is not working, I am just trying to get a simple result and print it to a canvas widget. When this gets working I will do the entire loan formula. As it is I get no output in the GUI or in the console.
Is this even possible to place the result of a calculation as text in canvas.create_text?
from tkinter import * # Import tkinter
width = 500
height = 500
class MainGUI:
def __init__(self):
window = Tk() # Create a window
window.title(" Loan Schedule ") # Set title
frame1 = Frame(window)
frame1.grid(row = 1, column = 1)
Label(frame1, text = " Loan Amount ").grid(row = 1, column = 1, sticky = W)
self.v1 = StringVar()
Entry(frame1, textvariable = self.v1, justify = RIGHT).grid(row = 1, column = 2)
Label(frame1, text = " Years ").grid(row = 1, column = 3, sticky = W)
self.v2 = StringVar()
Entry(frame1, textvariable = self.v2, justify = RIGHT).grid(row = 1, column = 4)
btCalculate = Button(frame1, text = " Calculate ", command = self.calculate()).grid(row = 1, column = 5, sticky = E)
frame2 = Frame(window)
frame2.grid(row = 2, column = 1)
self.canvas = Canvas(frame2, width = width, height = height, bg = "white")
self.canvas.pack()
self.canvas.create_text(25, 25, text = self.calculate(), tags = "text")
window.mainloop() # Create an event loop
def calculate(self):
result = self.v1.get() + self.v2.get()
print(result)
return result
MainGUI()
command require function name without ()
command = self.calculate
so now it works
from tkinter import * # Import tkinter
width = 500
height = 500
class MainGUI:
def __init__(self):
window = Tk() # Create a window
window.title(" Loan Schedule ") # Set title
frame1 = Frame(window)
frame1.grid(row = 1, column = 1)
Label(frame1, text = " Loan Amount ").grid(row = 1, column = 1, sticky = W)
self.v1 = StringVar()
Entry(frame1, textvariable = self.v1, justify = RIGHT).grid(row = 1, column = 2)
Label(frame1, text = " Years ").grid(row = 1, column = 3, sticky = W)
self.v2 = StringVar()
Entry(frame1, textvariable = self.v2, justify = RIGHT).grid(row = 1, column = 4)
btCalculate = Button(frame1, text = " Calculate ", command = self.calculate).grid(row = 1, column = 5, sticky = E)
frame2 = Frame(window)
frame2.grid(row = 2, column = 1)
self.canvas = Canvas(frame2, width = width, height = height, bg = "white")
self.canvas.pack()
self.canvas.create_text(55, 10, text = self.add_text(), tags = "text")
window.mainloop() # Create an event loop
def calculate(self):
result = int(self.v1.get()) + int(self.v2.get())
self.canvas.create_text(25, 25, text = result, tags = "text")
print(result)
return result
def add_text(self):
return "HELLO WORLD"
MainGUI()
by the way: line below means - run self.calculate() and result assign to command
command = self.calculate()

Cosinus drawing

I'd like to make a program which draws a cosinus graph in orderd range. But there is an error which I'm not able to repair. Error Message: "z = int(self.entry.get())
AttributeError: program instance has no attribute 'entry" Here is my code:
# -*- coding: utf-8 -*-
from Tkinter import Tk, W, E
from ttk import Label, Button, Frame, Entry,Style
import math
import sys
import matplotlib as mp
class program(Frame):
def __init__(self,main):
Frame.__init__(self,main)
self.main = main
self.initUI()
def initUI(self):
self.main.title('COSINUSEK')
Style().configure('TFrame', background = 'black')
Style().configure('TLabel', background = 'black', foreground = 'blue')
Style().configure("TButton", background = 'red', foreground = 'blue')
self.rowconfigure(0, pad = 3)
self.rowconfigure(1, pad = 3)
self.rowconfigure(2, pad = 3)
self.rowconfigure(3, pad = 3)
self.rowconfigure(4, pad = 3)
self.columnconfigure(0,pad =3)
self.columnconfigure(1,pad =3)
self.columnconfigure(2,pad =3)
self.columnconfigure(3,pad =3)
self.columnconfigure(4,pad =3)
label = Label(self, text = 'Podaj zakres w stopniach').grid(row = 0,column = 3)
od = Label(self, text = ' OD').grid(row = 1, column =0)
do = Label(self, text = ' DO').grid(row = 1, column =4 )
entry = Entry(self, justify = 'center').grid(row = 2,column = 0,columnspan = 2 ,sticky = E+ W)
entry1 = Entry(self, justify = 'center').grid(row = 2,column = 4,columnspan = 2, sticky = E)
button = Button(self, text = 'Ok',command = self.ok).grid(row = 3,column = 3)
button1 = Button(self, text = 'Draw', command = self.dra).grid(row = 4, column = 3)
self.pack()
def run(self):
self.main.mainloop()
def ok(self):
x = []
y = []
z = int(self.entry.get())
w = int(self.entry1.get())
i = w
while i in range(w,z):
x.append(i)
for a in x:
y[a] = math.cos((x[a]*math.pi)/180)
i = i + 0.01
def dra(self):
self.mp.ion()
self.mp.plot(self.x,self.y)
self.mp.title('Wykres')
self.mp.xlabel('x')
self.mp.ylabel('y')
self.mp.draw()
program(Tk()).run()
Replace:
entry = Entry(self, justify = 'center').grid(row = 2,column = 0,columnspan = 2 ,sticky = E+ W)
entry1 = Entry(self, justify = 'center').grid(row = 2,column = 4,columnspan = 2, sticky = E)
to
self.entry = Entry(self, justify = 'center')
self.entry.grid(row = 2,column = 0,columnspan = 2 ,sticky = E+ W)
self.entry1 = Entry(self, justify = 'center')
self.entry1.grid(row = 2,column = 4,columnspan = 2, sticky = E)
Otherwise, at line z = int(self.entry.get()), self.entry would not exist. Also, the grid method doesn't return anything so, if you do everything in one line as you did, you lose your Entry object and affect None to entry.
When making the variables, you'll have to set them as instance variables:
self.entry = Entry(self, justify = 'center').grid(row = 2,column = 0,columnspan = 2 ,sticky = E+ W)
self.entry1 = Entry(self, justify = 'center').grid(row = 2,column = 4,columnspan = 2, sticky = E)

Categories

Resources