Tkinter variable error - python

import sys
from tkinter import *
def printer():
print(message)
print(offset)
gui = Tk()
gui.title("Caesar Cypher Encoder")
Button(gui, text="Encode", command=printer).grid(row = 2, column = 2)
Label(gui, text = "Message").grid(row = 1, column =0)
Label(gui, text = "Offset").grid(row = 1, column =1)
message = Entry(gui)
message.grid(row=2, column=0)
offset = Scale(gui, from_=0, to=25)
offset.grid(row=2, column=1)
mainloop( )
When i run the above code with an input in both the input box and a value on the slider - it comes up with the ouput
.46329264
.46329296
How would i get it to display the string inputted into the text box, and the value selected on the slider

Use Entry.get, Scale.get methods:
def printer():
print(message.get())
print(offset.get())

Related

Bind function to multiple labels named equally - tkinter

I want to allow the user to create as many labels as they want using the following code:
def new_line(event):
global Row_n
Row_n = Row_n + 1
Choose= tk.Label(frame, text="Choose option", background = "white",font = ("Helvetica",13),fg = "blue")
Choose.grid(row = Row_n, column = 0, sticky = 'nsew')
return Row_n
root.bind('<Return>',lambda event:new_line(event))
That way, by pressing "Enter", the user can create as many "Choose" labels as they wish. But then I want for a second label to appear every time the user clicks on one of the "Choose" label. So I use the following code:
def second_l(event):
Row_n = Row_n+1
second_label = tk.Label(frame, text="Second label")
Choose.bind('<Button-1>',lambda event:second_l(event))
When I try to run this I get the following error:
can't invoke "bind" command: application has been destroyed
If I add "Choose" label outside the "new_line" function the "second_l" function will only work for that label. It won´t work for the labels generated by the "new_line" function.
Whole code:
import tkinter as tk#to create the gui
from tkinter import filedialog, Text #filedialog to pick apps and Text to display text
import os #Allows us to run apps
root = tk.Tk()
frame = tk.Frame(root,bg="white")
frame.place(relwidth=0.8,relheight=0.7,relx=0.1,rely=0.1)
Row_n=0
def new_line(event):
global Row_n
Row_n = Row_n + 1
Choose= tk.Label(frame, text="Choose option", background = "white",font = ("Helvetica",13),fg = "blue")
Choose.grid(row = Row_n, column = 0, sticky = 'nsew')
return Row_n
root.bind('<Return>',lambda event:new_line(event))
def second_l(event):
global Row_n
Row_n = Row_n+1
second_label = tk.Label(frame, text="Second label")
second_label.grid(row = Row_n, column = 0, sticky = 'nsew')
Choose.bind('<Button-1>',lambda event:second_l(event))
root.mainloop()
I am unable to understand why are you getting this error "can't invoke "bind" command" but I think, I understand your problem
you can try this:-
import tkinter as tk#to create the gui
from tkinter import filedialog, Text #filedialog to pick apps and Text to display text
import os #Allows us to run apps
root = tk.Tk()
frame = tk.Frame(root,bg="white")
frame.place(relwidth=0.8,relheight=0.7,relx=0.1,rely=0.1)
Row_n=0
Choose= tk.Label(frame, text="", background = "white",font = ("Helvetica",13),fg = "blue")
def new_line(event):
global Row_n
Row_n = Row_n + 1
Choose.config(text="Choose option")
Choose.grid(row = Row_n, column = 0, sticky = 'nsew')
return Row_n
root.bind('<Return>',lambda event:new_line(event))
def second_l(event):
global Row_n
Row_n = Row_n+1
second_label = tk.Label(frame, text="Second label")
second_label.grid(row = Row_n, column = 0, sticky = 'nsew')
Choose.bind('<Button-1>',lambda event:second_l(event))
root.mainloop()

Python: GUI based "reverse entry" using recursion failing

I am trying to make a Python program that asks the user for a number then reverses it using recursion. My attempt is below, but my code gives me TypeError: unsupported operand type(s) for //: 'Entry' and 'int' - any ideas?
from tkinter import *
def reverseInteger(n, r):
if n==0:
return r
else:
return reverseInteger(n//10, r*10 + n%10)
window = Tk()
window.title("Reverse Integer")
frame1 = Frame(window)
frame1.pack()
number = StringVar()
numEntry = Entry(frame1, textvariable=number)
btGetName = Button(frame1, text = "Calculate", command = reverseInteger(numEntry, 0))
label3 = Label(frame1)
numEntry.grid(row = 1, column = 1)
btGetName.grid(row = 1, column = 2)
label3.grid(row = 2, column = 1, sticky="w")
window.mainloop()
Your recursive function is perfectly fine but there are several other
problems in your code.
The main one is that the command parameter of Button must be the
function that will be called when the user presses on the buttton. In
your code, command is set to the return value of reverseInteger
which is an int. So there is a problem here.
Also it seems to me that you want to put the result of your
calculation in label3 so your StringVar should be attached to it
and not to numEntry.
So here is a version that seems ok to me:
from tkinter import *
def reverseInteger(n, r):
if n==0:
return r
else:
return reverseInteger(n//10, r*10 + n%10)
def reverse(): # called when the user click on the button
value = reverseInteger(int(numEntry.get()), 0)
number.set(value) # change the text of the label
window = Tk()
window.title("Reverse Integer")
frame1 = Frame(window)
frame1.pack()
number = StringVar()
numEntry = Entry(frame1)
btGetName = Button(frame1, text = "Calculate", command = reverse)
label3 = Label(frame1, textvariable=number)
numEntry.grid(row = 1, column = 1)
btGetName.grid(row = 1, column = 2)
label3.grid(row = 2, column = 1, sticky="w")
window.mainloop()

I'm unable to get a string out of tkinter entrybox

import random
import tkinter as tk
frame = tk.Tk()
frame.title("koeweils baldadige encyptor")
frame.geometry('400x200')
printButton = tk.Button(frame,text = "Print", command = lambda: zandkasteel())
printButton.pack()
freek = tk.Text(frame,height = 5, width = 20)
freek.pack()
input_a = freek.get(1.0, "end-1c")
print(input_a)
fruit = 0
fad = input_a[fruit:fruit+1]
print(fad)
schepje = len(input_a.strip("\n"))
print(schepje)
def zandkasteel():
lbl.config(text = "Ingevulde string: "+input_a)
with open("luchtballon.txt", "w") as chocoladeletter:
for i in range(schepje):
n = random.randint()
print(n)
leuk_woord = ord(fad)*n
print(leuk_woord)
chocoladeletter.write(str(leuk_woord))
chocoladeletter.write(str(n))
chocoladeletter.write('\n')
lbl = tk.Label(frame, text = "")
lbl.pack()
frame.mainloop()
I need to get the string that was entered into the text entry field freek. I have tried to assign that string to input_a, but the string doesn't show up.
Right now, input_a doesn't get anything assigned to it and seems to stay blank. I had the same function working before implementing a GUI, so the problem shouldn't lie with the def zandkasteel.
To be honest I really don't know what to try at this point, if you happen to have any insights, please do share and help out this newbie programmer in need.
Here are some simple modifications to your code that shows how to get the string in the Text widget when it's needed — specifically when the zandkasteel() function gets called in response to the user clicking on the Print button.
import random
import tkinter as tk
frame = tk.Tk()
frame.title("koeweils baldadige encyptor")
frame.geometry('400x200')
printButton = tk.Button(frame, text="Print", command=lambda: zandkasteel())
printButton.pack()
freek = tk.Text(frame, height=5, width=20)
freek.pack()
def zandkasteel():
input_a = freek.get(1.0, "end-1c")
print(f'{input_a=}')
fruit = 0
fad = input_a[fruit:fruit+1]
print(f'{fad=}')
schepje = len(input_a.strip("\n"))
print(f'{schepje=}')
lbl.config(text="Ingevulde string: " + input_a)
with open("luchtballon.txt", "w") as chocoladeletter:
for i in range(schepje):
n = random.randint(1, 3)
print(n)
leuk_woord = ord(fad)*n
print(leuk_woord)
chocoladeletter.write(str(leuk_woord))
chocoladeletter.write(str(n))
chocoladeletter.write('\n')
lbl = tk.Label(frame, text="")
lbl.pack()
frame.mainloop()

Turtle GUI improvement

I'm a 11th grader (5th year student) that just started studying Python programming. I am trying to make a GUI where I can chose what shape I want to draw with turtle and input the values needed to draw out the shape. I managed to do that with the following code (where I already did the functions of the turtle fractals and imported that file):
from tkinter import *
import turtlegraphics
from turtle import *
import math
#set up the window
root = Tk()
root.title('Turtle shapes')
root.geometry('300x200+100+100')
#make the interface
turtleLabel = Label(root, text = 'Turtle Fractals Generator')
turtleLabel.grid(row = 0, column =1, columnspan =2)
#order widgets
orderLabel = Label(root, text ='Order')
orderLabel.grid(row = 1, column =0)
orderStr = StringVar()
orderEntry = Entry(root, textvariable = orderStr)
orderEntry.grid(row = 1, column = 1, columnspan = 2)
#length widgets
lengthLabel = Label(root, text ='Length')
lengthLabel.grid(row = 2, column =0)
lengthStr = StringVar()
lengthEntry = Entry(root, textvariable = lengthStr)
lengthEntry.grid(row = 2, column = 1, columnspan = 2)
#button widgets
def clearF():
#Clear the entries
orderStr.set('')
lengthStr.set('')
return
#end def
clearButton = Button(root, text ='Clear', command = clearF)
clearButton.grid(row = 3, column =1)
def treeF():
order = int(orderStr.get())
length = float(lengthStr.get())
turtlegraphics.tree(order,length, pen)
return
#end def
treeButton = Button(root, text ='Tree', command = treeF)
treeButton.grid(row = 1, column =3)
#make a gasket button
def gasketF():
order = int(orderStr.get())
length = float(lengthStr.get())
turtlegraphics.gasket(order,length,pen)
return
#end def
gasButton = Button(root, text ='Gasket', command = gasketF)
gasButton.grid(row = 2, column =3)
#make a dandelion button
def dandelionF():
order = int(orderStr.get())
length = float(lengthStr.get())
turtlegraphics.tree4(order,length,pen)
return
#end def
danButton = Button(root, text ='Dandelion', command = dandelionF)
danButton.grid(row = 3, column =3)
#make flalke button
def kevinF():
order = int(orderStr.get())
length = float(lengthStr.get())
turtlegraphics.k(order,length,pen)
return
#end def
def flakeF():
order = int(orderStr.get())
length = float(lengthStr.get())
turtlegraphics.flake(order,length,pen)
return
#end def
flakeButton = Button(root, text ='Flake', command = flakeF)
flakeButton.grid(row = 4, column =3)
#make a screen and a pen
pen = Pen()
screen = Screen()
pen.speed(0)
pen.color('blue')
pen.width(3)
screen.bgcolor('white')
root.mainloop()
However, I want to try and put a list to chose the shape from rather than having several buttons. I don't understand much about lists due to the fact that I wasn't taught it yet but after doing research this is what I got:
'''
program gui to draw turtle fractals
'''
from tkinter import *
import turtlegraphics
from turtle import *
import math
#make a screen and a pen
pen = Pen()
def treeF():
order = int(orderStr.get())
length = float(lengthStr.get())
turtlegraphics.tree(order,length, pen)
return
#end def
#make a gasket button
def gasketF():
order = int(orderStr.get())
length = float(lengthStr.get())
turtlegraphics.gasket(order,length,pen)
return
#end def
#make a dandelion button
def dandelionF():
order = int(orderStr.get())
length = float(lengthStr.get())
turtlegraphics.tree4(order,length,pen)
return
#end def
#make flalke button
def kevinF():
order = int(orderStr.get())
length = float(lengthStr.get())
turtlegraphics.k(order,length,pen)
return
#end def
def flakeF():
order = int(orderStr.get())
length = float(lengthStr.get())
turtlegraphics.flake(order,length,pen)
return
#end def
screen = Screen()
pen.speed(0)
pen.color('blue')
pen.width(3)
screen.bgcolor('white')
#set up the window
root = Tk()
root.title('turtle shapes')
root.geometry('600x300+100+100')
#make the interface
turtleLabel = Label(root, text = 'Turtle Fractals Generator')
turtleLabel.grid(row = 0, column =1, columnspan =2)
#order widgets
orderLabel = Label(root, text ='Order')
orderLabel.grid(row = 1, column =0)
orderStr = StringVar()
orderEntry = Entry(root, textvariable = orderStr)
orderEntry.grid(row = 1, column = 1, columnspan = 2)
#length widgets
lengthLabel = Label(root, text ='Length')
lengthLabel.grid(row = 2, column =0)
lengthStr = StringVar()
lengthEntry = Entry(root, textvariable = lengthStr)
lengthEntry.grid(row = 2, column = 1, columnspan = 2)
#button widgets
def clearF():
#Clear the entries
orderStr.set('')
lengthStr.set('')
return
#end def
clearButton = Button(root, text ='Clear', command = clearF)
clearButton.grid(row = 3, column =1)
#list
def selection():
obj = nameList.curselection()[0]
if obj == 'tree':
command = treeF
return
if obj == 'dandelion':
command = dandelionF
return
if obj == 'flake':
command = flakeF
return
if obj == 'gasketF':
command = gasketF
return
#end if
#end def
#create list
listbox = Listbox(root,selectmode = SINGLE) #select mode is type of
selection
listButton= Button(root, text = 'chose fractal')
labelVar = StringVar()
nameLabel = Label(root, textvariable = labelVar)
nameLabel.grid(row = 2 , column = 7, columnspan = 2)
labelVar.set('choose a fractal')
names = ['tree','dandelion','flake','gasket']
nameList = Listbox(root)
for i in names:
nameList.insert(END, i)
nameList.grid(row = 4, column =7, columnspan = 2)
selectionButton = Button(root, text = 'draw', command = selection)
selectionButton.grid(row = 5, column = 7, columnspan = 2)
root.mainloop()
I know something is wrong with my code, but I can't tell what I did wrong. When I run my code I get no error whatsoever, but it does not draw the shape. In addition, the clear button does not do its function when clicked. How can I can I fix this?
Your immediate problem is how selection() works -- it was comparing numbers to strings and have the code necessary to execute any of the subprograms. I've reworked it below to get the behavior you desire. I've also made other changes and simplifications:
from tkinter import *
from turtle import Pen, Screen
import turtlegraphics
def treeF():
order = int(orderEntry.get())
length = float(lengthEntry.get())
turtlegraphics.tree(order, length, pen)
def dandelionF():
order = int(orderEntry.get())
length = float(lengthEntry.get())
turtlegraphics.tree4(order, length, pen)
def flakeF():
order = int(orderEntry.get())
length = float(lengthEntry.get())
turtlegraphics.flake(order, length, pen)
def gasketF():
order = int(orderEntry.get())
length = float(lengthEntry.get())
turtlegraphics.gasket(order, length, pen)
def kevinF():
order = int(orderEntry.get())
length = float(lengthEntry.get())
turtlegraphics.k(order, length, pen)
fractals = [('tree', treeF), ('dandelion', dandelionF), ('flake', flakeF), ('gasket', gasketF), ('kevin', kevinF)]
# make a screen and a pen
screen = Screen()
screen.bgcolor('white')
pen = Pen()
pen.speed('fastest')
pen.color('blue')
pen.width(3)
# set up the window
root = Tk()
root.title('turtle shapes')
root.geometry('600x400+100+100')
# make the interface
turtleLabel = Label(root, text='Turtle Fractals Generator')
turtleLabel.grid(row=0, column=1, columnspan=2)
# order widgets
orderLabel = Label(root, text='Order')
orderLabel.grid(row=1, column=0)
orderEntry = Entry(root)
orderEntry.grid(row=1, column=1, columnspan=2)
# length widgets
lengthLabel = Label(root, text='Length')
lengthLabel.grid(row=2, column=0)
lengthEntry = Entry(root)
lengthEntry.grid(row=2, column=1, columnspan=2)
# button widgets
def clearF():
# Clear the entries
orderEntry.delete(0, 'end')
lengthEntry.delete(0, 'end')
clearButton = Button(root, text='Clear', command=clearF)
clearButton.grid(row=3, column=1)
# list
def selection():
selections = nameList.curselection()
if selections:
selection = selections[0]
if selection < len(fractals):
name, definition = fractals[selection]
definition()
# create list
listbox = Listbox(root, selectmode=SINGLE) # select mode is type of selection
listButton = Button(root, text='chose fractal')
labelVar = StringVar()
nameLabel = Label(root, textvariable=labelVar)
nameLabel.grid(row=2, column=7, columnspan=2)
labelVar.set('choose a fractal')
nameList = Listbox(root)
for name, definition in fractals:
nameList.insert(END, name)
nameList.grid(row=4, column=7, columnspan=2)
selectionButton = Button(root, text='Draw', command=selection)
selectionButton.grid(row=5, column=7, columnspan=2)
root.mainloop()
General comments about your code:
Find and follow a good Python coding style -- it makes understanding your code more difficult when you invent your own coding "style".
This isn't the correct way to integrate turtle with tkinter. Search StackOverflow, or the turtle documentation, for RawTurtle and TurtleScreen, the classes you use instead of Turtle (aka Pen) and Screen when embedding in an existing Tk window structure.

Getting and calculating stuff through tkinter widets

I was wondering how to calculate stuff using tkinter buttons. I'm making a simple program to calculate seconds to hours:minutes:seconds. The user inputs an integer using the entry widget on the seconds box and when they press calculate, they get the result via the converted time line. I'm confused on how to start calculating it. I know you get the integer via .get, but I'm stuck on how to do that and calculate it in a h:m:s format. This is my code so far.
import tkinter
from tkinter import *
class TimeConverterUI():
def __init__(self):
self.root_window = Tk()
self.root_window.geometry('400x150')
self.root_window.title('Seconds Converter')
self.text()
self.calculate_button()
self.quit_button()
self.root_window.wait_window()
def text(self):
row_label = tkinter.Label(
master = self.root_window, text = 'Seconds: ')
row_label.grid( row = 0, column = 0, columnspan=2, padx=10, pady=10,
sticky = tkinter.W)
secondsEntry = Entry(master = self.root_window)
secondsEntry.grid(row = 0, column = 1)
row_label = tkinter.Label(
master = self.root_window, text = 'Converted Time(H:M:S): ').grid(row=1)
def calculate_button(self):
quit = Button(self.root_window, text = "Calculate", command = self.calculate)
quit.grid(row = 3, column = 0, columnspan = 3, pady=20,
sticky = tkinter.W)
def calculate(self):
pass
def quit_button(self):
quit = Button(self.root_window, text = "Quit", command = self.quit)
quit.grid(row = 3, column = 3, columnspan = 3, pady=20,
sticky = tkinter.E)
def quit(self) -> bool:
self.root_window.destroy()
return True
if __name__ == '__main__':
convert=TimeConverterUI()
First break this code below into 2 lines if you ever want to use row_label later because this will return NoneType. You should define it first then use .grid on it (just like your button).
row_label = tkinter.Label(
master = self.root_window, text = 'Converted Time(H:M:S): ').grid(row=1)
Now you can create another label to show the result. Remember to put self. before its name so you can use it in the calculate function. Also change secondsEntry to self.secondsEntry for the same reason.Now you just use int(self.secondsEntry.get()) in that function and do the required calculations. Then set the result to that result label with .configure(text=str(result))

Categories