What caused the error - python

I am trying to make GUI that reverses the user input but something is wrong
from tkinter import *
from tkinter.ttk import *
def reverse(s):
s=U.get()
return s[::-1]
root=Tk(className="Reverse your text")
la=Label(root, text="Enter text to reverse")
la.pack()
U=Entry(root,textvariable=s)
U.pack()
BT=Button(root, text="reverse", command=reverse(s))
BT.pack()
root.mainloop()
Error: U=Entry(root,textvariable=s)
NameError: name 's' is not defined

def reverse(s): should not have an s if you don't intend to pass any arguments to the function. Likewise for command=reverse(s)
U=Entry(root,textvariable=s) does not need a textvariable if you're just going to access the Entry's value directly with .get. And anyway, you can't use s here, because you never assigned a StringVar object to s to begin with.
The value returned by return s[::-1] will not be visible in any way to the user. If you want to show the reversed string, you need to print it or insert it into the entry, or similar.
from tkinter import *
from tkinter.ttk import *
def reverse():
s=U.get()
U.delete(0, END)
U.insert(0,s[::-1])
root=Tk(className="Reverse your text")
la=Label(root, text="Enter text to reverse")
la.pack()
U=Entry(root)
U.pack()
BT=Button(root, text="reverse", command=reverse)
BT.pack()
root.mainloop()
Result:

Related

Tkinter Passing StringVar.get through command lambda gives initial value

Okay, so I am trying to make a menu system using Tkinter and am trying to save the string value of the drop down menu to a class variable. I have code to handle that part, but the problem comes with getting that string value to the function I have written. I know that it isn't my function that is the problem as I am using the print function for my example below.
import tkinter as tk
from enum import Enum
class CustomEnum(Enum):
Option1 = 'Option1'
Option2 = 'Option2'
class window():
def __init__(self, root):
self.value = CustomEnum.Option1
test = tk.StringVar()
test.set(self.value.value)
tk.OptionMenu(root, test, *[e.value for e in CustomEnum], command = lambda
content = test.get() : print(content)).pack()
tk.Button(root, text="Save",
command = lambda content = test.get() : print(content)).pack()
root = tk.Tk()
test = window(root)
root.mainloop()
If you run this code, it'll constantly print "Option 1" despite what option you chose or if you add or remove elements (aside from removing Option 1).
The problem lies in this line
tk.Button(root, text="Save",
command = lambda content = test.get() : print(content)).pack()
You are assigning content the value of test.get() which was at that instant (Option1) and it continues to be so unchanged.
Since you want the current value of test.get(), you would have to do this
command = lambda: print(test.get())).pack()
Also, I believe you have misspelt customEnum instead of CustomEnum.

What arguments should I give when I call the function I created for bind in tkinter

Here is an example of a problem:
from tkinter import ttk
from tkinter import *
root = Tk()
combobox1 = ttk.Combobox(root, values = ('Jan', 'Feb', 'August'))
combobox1.pack()
comb2 = ttk.Combobox(root, state=DISABLED)
comb2.pack()
def comb1_selected(*args):
someword = ""
if combobox1.get() == 'Jan':
someword = 'J'
comb2.config(state='normal')
comb2.config(values=someword)
return someword
def use_comb1_selected():
print(comb1_selected(*args))
use_comb1_selected() #What arguments should I give here??
combobox1.bind("<<ComboboxSelected>>", comb1_selected)
root.mainloop()
I can't figure out which arguments to give to the function I created
Attempting to give arguments like "event" caused the following error
NameError: name 'event' is not defined
And without the argument, the function did nothing, even though it was supposed to be printed 'J'
Please help me understand what I need to do

Retrieving value from Tkinter combobox

Eventually I want to use the values in the comboboxes as parameters in other functions, but I think if I can just get them to print for now, that will be enough to build off of. Here's what I have so far.
import tkinter as tk
from tkinter import ttk
import time
def ok():
betType = betTypeVar.get()
season = seasonVar.get()
print(betType, season)
def CreateSimPreviousSeasonWindow():
prevSeasonWindow = tk.Tk()
#============= Bet Type Input =============#
betTypeVar = tk.StringVar()
betTypeLabel = tk.Label(prevSeasonWindow, text="Bet type:").grid(row=0,column=0)
betTypeChosen = ttk.Combobox(prevSeasonWindow, values=['Moneyline','Total'])
betTypeChosen.grid(row=0, column=1)
seasonVar = tk.StringVar()
seasonLabel = tk.Label(prevSeasonWindow, text='Season:').grid(row=1, column=0)
seasonChosen = ttk.Combobox(prevSeasonWindow, values=['2018', '2017'])
seasonChosen.grid(row=1,column=1)
button = tk.Button(prevSeasonWindow, text='OK', command=ok)
button.grid(row=2,column=0)
prevSeasonWindow.mainloop()
This gives me
File "C:[directory...]", line 6, in ok
betType = betTypeVar.get()
NameError: name 'betTypeVar' is not defined
To me it looks pretty obvious that this error is because ok() doesn't have any parameters passed to it, so it has no idea what 'betTypeVar' is, but all the tutorials I've read do it this way, so I'm missing something. If I try actually passing ok() the arguments, it still doesn't work.
There are two things to fix in your code. First let's focus on CreateSimPreviousSeasonWindow:
betTypeVar = tk.StringVar()
seasonVar = tk.StringVar()
You defined two StringVar but you actually never used it or linked them to your combobox object. The correct way is to set them as a textvaraible:
betTypeChosen = ttk.Combobox(prevSeasonWindow, textvariable=betTypeVar, values=['Moneyline','Total'])
seasonChosen = ttk.Combobox(prevSeasonWindow, textvariable=seasonVar, values=['2018', '2017'])
Next, NameError: name 'betTypeVar' is not defined is due to your variables being local variables. You are trying to access the same variable across different functions. To pass them around, you need to declare global:
def ok():
global betTypeVar, seasonVar
betType = betTypeVar.get()
season = seasonVar.get()
print(betType, season)
def CreateSimPreviousSeasonWindow():
global betTypeVar, seasonVar
...
Also I want to point out that if you just want to retrieve the values of the combobox, you don't really need to create two StringVar. Just combobox.get() already works good enough.
import tkinter as tk
from tkinter import ttk
import time
def ok():
global betTypeChosen, seasonChosen
print (betTypeChosen.get(), seasonChosen.get())
def CreateSimPreviousSeasonWindow():
global betTypeChosen,seasonChosen
prevSeasonWindow = tk.Tk()
#============= Bet Type Input =============#
betTypeLabel = tk.Label(prevSeasonWindow, text="Bet type:").grid(row=0,column=0)
betTypeChosen = ttk.Combobox(prevSeasonWindow,values=['Moneyline','Total'])
betTypeChosen.grid(row=0, column=1)
seasonLabel = tk.Label(prevSeasonWindow, text='Season:').grid(row=1, column=0)
seasonChosen = ttk.Combobox(prevSeasonWindow, values=['2018', '2017'])
seasonChosen.grid(row=1,column=1)
button = tk.Button(prevSeasonWindow, text='OK', command=ok)
button.grid(row=2,column=0)
prevSeasonWindow.mainloop()
CreateSimPreviousSeasonWindow()

How to get content of ScrolledText?

I'm trying to get content of a ScrolledText but so far success is not with me :)
I don't understand where i'm wrong.
Here a very simple example of not working code...
from Tkinter import Tk
from ScrolledText import ScrolledText
def returnPressed(value):
print "CONTENT: " + value
root = Tk()
st = ScrolledText(root)
st.bind("<Return>", lambda event, i=st.get("1.0", "end-1c"): returnPressed(i))
st.insert("insert", "TEST")
st.pack()
root.mainloop()
Ok this is because of lambda definition.
By this way, function is created with constant "i" value, which is the value at declaration of function.
By rewording lambda as it, it works!
st.bind("<Return>", lambda event: returnPressed(st.get("1.0", "end-1c")))
You are getting the value at the time you create the button, which means the value will always be empty. You need to get the value at the time that the event is processed.
You should avoid using lambda, it is a somewhat advanced concept that in this case adds complexity without adding any value. Simply get the value from within the function:
def returnPressed(event):
value = event.widget.get("1.0", "end-1c")
print "CONTENT: " + value
...
st.bind("<Return>", returnPressed)

How to get the user to enter a float in entry box?

If I create an entry box like so:
myentry = Entry ()
myentry.place (x = 54,y = 104)
the value that the user enters is a string value. What do I have to add so that the entry is a float? I have tried to write "float" in the parentheses beside Entry but it didn't work and showed me an error saying that tk() does not support float. Any help would be appreciated!
I wrote a simple script to demonstrate how to do what you want:
from Tkinter import Tk, Button, Entry, END
root = Tk()
def click():
"""Handle button click"""
# Get the input
val = myentry.get()
try:
# Try to make it a float
val = float(val)
print val
except ValueError:
# Print this if the input cannot be made a float
print "Bad input"
# Clear the entrybox
myentry.delete(0, END)
# Made this to demonstrate
Button(text="Print input", command=click).grid()
myentry = Entry()
myentry.grid()
root.mainloop()
When you click the button, the program tries to make the text in the entrybox a float. If it can't, it prints "Bad input". Otherwise, it prints the float in the terminal.

Categories