Graphic InterfaceTkinter Python - python

I´m having a problem with my interface using Tkinter in Python. I would like to put the phrase "Primeira cesta" and the button "Aplicar", at the top of the interface, not at the bottom. After that, I would like that comes the dropdown.
Can anybody help me, please?
Code
from tkinter import*
class Application():
def init(self, master):
mainframe = Frame(root)
mainframe.grid(column=0, row=0,sticky=(N,W,E,S))
mainframe.columnconfigure(0, weight = 1)
mainframe.rowconfigure(0, weight = 1)
mainframe.pack(pady = 100, padx = 100)
#color1
self.widget1 = Frame(master)
self.widget1.pack(side=TOP)
self.msg = Label(self.widget1, text="Primeira cesta")
self.msg["font"]=("Times New Roman", "12", "italic", "bold")
self.msg.pack()
self.aplicar=Button(self.widget1)
self.aplicar["text"]="Aplicar"
self.aplicar["font"]=("Calibri","10")
self.aplicar["width"]=5
self.aplicar["command"]=self.mudarTexto
self.aplicar.pack()
#Dropdown1
# Create a Tkinter variable
tkvar = StringVar(root)
tkvar2 = StringVar(root)
# Dictionary with options
cores = { 'Amarelo','Azul','Verde','Vermelho'}
formatos = {'2x1','2x2','2x3','2x4'}
tkvar.set('Cores') # set the default option
tkvar2.set('Formatos')
popupMenu = OptionMenu(mainframe, tkvar, *cores)
label1=Label(mainframe, text="Escolha uma cor")
label1.grid(row=1, column=1)
popupMenu.grid(row = 2, column =1)
popupMenu2 = OptionMenu(mainframe, tkvar2, *formatos)
label2=Label(mainframe, text="Escolha um formato")
label2.grid(row=3,column=1)
popupMenu2.grid(row = 4, column =1)
# on change dropdown value
def change_dropdown(*args):
print( tkvar.get() )
def change_dropdown2(*args):
print( tkvar2.get() )
# link function to change dropdown
tkvar.trace('w', change_dropdown)
tkvar2.trace('w', change_dropdown2)
def mudarTexto(self):
if self.msg["text"]=="Primeira cesta":
self.msg["text"]="A primeira cesta foi configurada"
else:
self.msg["text"]="Primeira cesta"
root=Tk()
Application(root)
root.mainloop()
enter image description here

Related

Newbie problem with using tkinter checkbutton in a class

Running python 3.8 in PyCharm
I'm trying to create a class to allow creation of a tkinter checkbutton (and eventually other widgets) that will hold all the formatting and definition for the widget. I would like to be able to test the state of the checkbutton and act on it in a callback. But like many others, my checkbutton variable seems to always be 0. I'm fairly sure its a garbage collection issue, but I can't figure a way around it. Note the second set of parameters in the class definition specify the location of the label to display the checkbutton variable state. At the moment, the callback is just to display the variable state in a label.
Acknowledgement:
I modified code from Burhard Meier's book "Python GUI Programming Cookbook" for this. The code related to the class is mine, the rest is from Burkhard Meier.
'''
This is a modification of code by Burhard A. Meier
in "Python GUI Programming Cookbook"
Created on Apr 30, 2019
#author: Burkhard A. Meier
'''
#======================
# imports
#======================
import tkinter as tk
from tkinter import ttk
# Create instance
win = tk.Tk()
# Add a title
win.title("GUI Test Box")
# Modify adding a Label
a_label = ttk.Label(win, text="Testing TK Widgets")
a_label.grid(column=0, row=0)
# Modified Button Click Function
def click_me():
action.configure(text='Hello ' + name.get() + ' ' +
number_chosen.get())
#Define the Checkbutton Class
class ChkBut(): #lable, xloc, yloc, xlab, ylab
def __init__(self, lable, xloc, yloc, xlab, ylab): # , xloc, yloc, text="default", variable = v, onvalue='Set', offvalue='NotSet'):
v = tk.IntVar()
self.v = v
self.lable = lable
self.xloc = xloc
self.yloc = yloc
self.xlab = xlab
self.ylab = ylab
c = tk.Checkbutton(
win,
text= self.lable,
variable=self.v,
command=self.cb(self.v, xlab,ylab))
c.grid(column=xloc, row=yloc, sticky = tk.W)
c.deselect()
def cb (self, c, xlab, ylab):
if c.get()==1:
c_label = ttk.Label(win, text="Set")
c_label.grid(column=xlab, row=ylab)
elif c.get()==0:
c_label = ttk.Label(win, text="NotSet")
c_label.grid(column=xlab, row=ylab)
else:
c_label = ttk.Label(win, text=c.v.get())
c_label.grid(column=xlab, row=ylab)
# Changing the Label
ttk.Label(win, text="Enter a name:").grid(column=0, row=0)
# Adding a Textbox Entry widget
name = tk.StringVar()
name_entered = ttk.Entry(win, width=12, textvariable=name)
name_entered.grid(column=0, row=1)
# Adding a Button
action = ttk.Button(win, text="Click Me!", command=click_me)
action.grid(column=2, row=1)
# Creating three checkbuttons
ttk.Label(win, text="Choose a number:").grid(column=1, row=0)
number = tk.StringVar()
number_chosen = ttk.Combobox(win, width=12, textvariable=number, state='readonly')
number_chosen['values'] = (1, 2, 4, 42, 100)
number_chosen.grid(column=1, row=1)
number_chosen.current(0)
check1 = ChkBut("Button 1", 0, 4, 0, 5)
chVarUn = tk.IntVar()
check2 = tk.Checkbutton(win, text="UnChecked", variable=chVarUn)
check2.deselect()
check2.chVarUn = 0
check2.grid(column=1, row=4, sticky=tk.W)
chVarEn = tk.IntVar()
check3 = tk.Checkbutton(win, text="Enabled", variable=chVarEn)
check3.select()
check3.chVarEn = 0
check3.grid(column=2, row=4, sticky=tk.W)
name_entered.focus() # Place cursor into name Entry
#======================
# Start GUI
#======================
win.mainloop()

problem with tkinter under defined function

Can you please help me with follwing issue I face:
When I am creating radiobutton with tkinter, I don't have a problem to select from the list.
However, if I put the same script under a menu, then selected option is always the default one, ("Python",1) in this specific case. Do you have any idea how to overcome this? Thanks in advance!
import tkinter as tk
root_m = tk.Tk()
root_m.geometry("400x200")
frame_m = tk.Frame(root_m)
root_m.title("NUMERIC UNIVERSE")
frame_m.pack()
def chars_merging():
languages = [
("Python",1),
("Perl",2),
("Java",3),
("C++",4),
("C",5)
]
root = tk.Tk()
root.geometry("400x200")
frame = tk.Frame(root)
root.title("SELECT SOMETHING")
frame.pack()
v = tk.IntVar()
v.set(0) # initializing the choice, i.e. Python
label = tk.Label(frame,
text="""Choose your favourite
programming language:""",
justify = tk.LEFT,
padx = 20)
label.pack()
def ShowChoice():
global data_sel
data_sel = v.get()
print(data_sel)
for val, language in enumerate(languages):
tk.Radiobutton(frame,
text=language,
indicatoron = 0,
width = 20,
padx = 20,
variable=data_sel,
command=ShowChoice,
value=val).pack(anchor=tk.W)
root.mainloop()
#return(languages[v.get()])
print("You selected", languages[v.get()])
button3 = tk.Button(frame_m,
text="3.Prepare and merge chars",
command=chars_merging,
width=25)
button3.pack()
# CLOSING THE WINDOW ---------------------------------------------------------
def finish():
root_m.destroy()
button_n = tk.Button(frame_m,
text="Finish",
command=finish,
width=25)
button_n.pack()
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
root_m.mainloop()

How to open a new frame from a current window in python tkinter?

class Login:
def __init__(self):
Label1 = Label(root,text = "Username")
Label2 = Label(root,text = "Password")
self.Entry1 = Entry(root)
self.Entry2 = Entry(root,show = "*")
Label1.grid(row=0)
Label2.grid(row=1)
self.Entry1.grid(row = 0,column = 1)
self.Entry2.grid(row = 1,column = 1)
root.minsize(width = 300,height = 80)
##new_window_button = Button(text="new window", command = ????)
##new_window_button.grid(columnspan = 2)
lgbutton = Button(text = "Login",command = self.ButtonClicked)
lgbutton.grid(columnspan = 2)
def ButtonClicked(self):
username = self.Entry1.get()
password = self.Entry2.get()
GetDatabase(username,password)
Currently this is what I have to create a window, however I want it to that when the new_window_button is clicked, the new page has its own widgets. I've used Toplevel before but it creates a child window without the widgets. Instead, the widgets are added to the parent window.
Judging by the comments it looks as though you are struggling with declaring the correct parent for widgets.
When a widget is declared the first parameter passed in to it is it's parent. For example:
Label(root, text="I'm in the root window.")
# ^ This is the parent
As opposed to:
Label(top, text="I'm in the top window.")
# ^ This is the parent
Please see a more fleshed out example below:
from tkinter import *
root = Tk()
top = Toplevel(root)
label1 = Label(root, text="I'm a placeholder in your root window.")
label2 = Label(top, text="I'm a placeholder in your top window.")
label1.pack()
label2.pack()
root.mainloop()
import tkinter
from tkinter import *
class LoginForm(Frame):
def __init__(self,master=None):
super().__init__(master)
self.pack()
self.createWidget()
def createWidget(self):
self.lblEmailId=Label(self,text="Email Id")
self.lblEmailId.grid(row=0,column=0)
self.varEmailid=StringVar()
self.txtEmailId=Entry(self,textvariable=self.varEmailid)
self.txtEmailId.grid(row=0,column=1)
self.txtEmailId.bind("<KeyRelease>",self.key_press)
self.lblPassword = Label(self, text="Password")
self.lblPassword.grid(row=1, column=0)
self.varPassword=StringVar()
self.txtPassword= Entry(self, textvariable=self.varPassword)
self.txtPassword.grid(row=1, column=1)
self.btnLogin=Button(self,text="Login")
self.btnLogin.grid(row=2,column=1)
self.btnLogin.bind("<Button-1>",self.btnLogin_click)
def btnLogin_click(self,event):
self.varPassword.set(self.varEmailid.get())
LoginWindow=Toplevel()
def key_press(self,event):
self.varPassword.set(self.varEmailid.get())
root=Tk()
fromLogin=LoginForm(root)
root.mainloop()

How to store values from an Entry widget for loop in tkinter?

This should be a very very simple problem. I'm making a GUI in which I have multiple entry widgets... about 30 or so all in one column. Instead of making each box one by one it seems like a better idea to just generate the widgets with a loop. However, I'm finding it extremely difficult to .get() values from the entry widgets, and convert them into floats. This is what I have so far... any help would be greatly appreciated.
class Application(Frame):
def __init__(root,master):
Frame.__init__(root,master)
root.grid()
root.create_widgets()
def calcCR(root):
d1 = root.enter.get()
d1 = float(d1)
#root.answer.delete(0.0,END)
a = 'The C/R Alpha is! %lf \n' % (d1)
root.answer.insert(0.0, a)
def create_widgets(root):
### Generate Element List ###
for i in range(len(elem)):
Label(root, text=elem[i]).grid(row=i+1, column=0)
### Generate entry boxes for element wt% ###
for i in range(len(elem)):
enter = Entry(root, width = 8)
enter.grid(row = i+1,column=1)
enter.insert(0,'0.00')
root.button = Button(root, text = 'Calculate C/R', command = root.calcCR)
root.button.grid(row=11, column=2, sticky = W, padx = 10)
root.answer = Text(root, width = 50, height = 12.5, wrap = WORD)
root.answer.grid(row=1, column=2, rowspan = 10, sticky = W, padx = 10)
root = Tk()
root.title('C/R Calculator')
app = Application(root)
root.mainloop()
Put the Entry instances into a list.
from tkinter import Tk, Frame, Label, Entry, Button
class App(Frame):
def __init__(root, master):
Frame.__init__(root, master)
root.grid()
root.create_widgets()
def get_values(root):
return [float(entry.get()) for entry in root.entries]
def calc_CR(root):
answer = sum(root.get_values()) #Replace with your own calculations
root.answer.config(text=str(answer))
def create_widgets(root):
root.entries = []
for i in range(20):
label = Label(root, text=str(i))
label.grid(row=i, column=0)
entry = Entry(root, width=8)
entry.grid(row=i, column=1)
entry.insert(0, '0.00')
root.entries.append(entry)
root.calc_button = Button(root, text='Calculate C/R', command=root.calc_CR)
root.calc_button.grid(row=20, column=0)
root.answer = Label(root, text='0')
root.answer.grid(row=20, column=1)
def run(root):
root.mainloop()
root = Tk()
root.title('C/R Calculator')
app = App(root)
app.run()

Python tkinter: access child widgets of a widget

I have a string 'currentMessage' and a Label to display it.
I have a Toplevel widget, which contains a Text widget to provide new value for 'currentMessage':
from tkinter import *
from tkinter import ttk
root = Tk()
mainFrame = ttk.Frame(root)
mainFrame.grid()
currentMessage = 'current Message'
ttk.Label(mainFrame, text = currentMessage).grid(padx = 10, pady = 10)
def updateCurrentMessage(popupWindow):
currentMessage = popupWindow.textBox.get(0.0, END)
def changeValues():
popup = Toplevel(mainFrame)
popup.grid()
textBox = Text(popup, width = 20, height = 5)
textBox.grid(column = 0, row = 0)
textBox.insert(END, 'new message here')
b = ttk.Button(popup, command = lambda: updateCurrentMessage(popup))
b.grid(column = 0, row = 1, padx = 5, pady = 5)
b['text'] = 'Update'
theButton = ttk.Button(mainFrame, command = changeValues, text = 'Click')
theButton.grid(padx = 10, pady = 10)
mainFrame.mainloop()
I tried to get the content of 'textBox' Text widget of the Toplevel by using this function:
def updateCurrentMessage(popupWindow):
currentMessage = popupWindow.textBox.get(0.0, END)
But I got an error
'Toplevel' object has no attribute 'textBox'
So how do I access content of the widget 'textBox', which is a child widget of 'popup' (this Toplevel widget is only created when function changeValues() is called)?
I think probably this is what you are looking for -- although I'm just guessing, because you are asking for a solution for a specific problem you think you have, however if I were you I would rethink what exactly do I want to do:
from tkinter import *
from tkinter import ttk
# Create Tk Interface root
root = Tk()
# Initialize mainFrame
mainFrame = ttk.Frame( root )
mainFrame.grid()
# Initialize label of mainframe
theLabel = ttk.Label( mainFrame, text='Current Message' )
theLabel.grid( padx=10, pady=10 )
def createPopup():
# Initialize popup window
popup = Toplevel( mainFrame )
popup.grid()
# Initialize text box of popup window
textBox = Text( popup, width=20, height=5 )
textBox.grid( column = 0, row = 0 )
textBox.insert( END, 'New Message Here' )
# Initialize button of popup window
button = ttk.Button( master = popup,
command = lambda: theLabel.config(text=textBox.get(0.0, END)),
text = 'Update')
button.grid( column=0, row=1, padx=5, pady=5 )
# Initialize button of main frame
theButton = ttk.Button( mainFrame, command=createPopup, text='Click' )
theButton.grid( padx=10, pady=10 )
# Enter event loop
mainFrame.mainloop()
There is a way indeed, like this:
def updateCurrentMessage(popupWindow):
currentMessage = popupWindow.nametowidget('textBox').get(0.0, END)
def changeValues():
popup = Toplevel(mainFrame)
popup.grid()
textBox = Text(popup, width = 20, height = 5, name = 'textBox')
textBox.grid(column = 0, row = 0)
textBox.insert(END, 'new message here')
b = ttk.Button(popup, command = lambda: updateCurrentMessage(popup))
b.grid(column = 0, row = 1, padx = 5, pady = 5)
b['text'] = 'Update'
You can choose whatever you want for the 'name'.

Categories