Whats wrong with this GUI program? - it says 'tra' is not defined - python

im a beginner programer and made this GUI ceasar code encrypter. I based it on a normal python program i made earlier, and i think i changed sufficiently, but evidently i didnt as it doesnt work. It tells me that the variable 'tra' is not defined.
The program:
from tkinter import *
class Application(Frame):
def __init__(self, master):
super(Application, self).__init__(master)
self.grid()
self.createwidgets()
def createwidgets(self):
Label(self,
text = "Encrypt a message:",
).grid(row = 0, column = 0, columnspan = 2, sticky = W)
Label(self,
text = "Whats your message?:",
).grid(row = 1, column = 0, sticky = W)
self.messageent = Entry(self)
self.messageent.grid(row = 3, column = 0, sticky = W)
Label(self,
text = "Whats the key?:(1 - 25)",
).grid(row = 4, column = 0, sticky = W)
self.keyent = Entry(self)
self.keyent.grid(row = 5, column = 0, sticky = W)
Button(self,
text = "Click for coded message",
command = self.encrypt
).grid(row = 6, column = 0, sticky = W)
self.messagetxt = Text(self, width = 75, height = 10, wrap = WORD)
self.messagetxt.grid(row = 7, column = 0, columnspan = 4)
def things():
message = self.messageent.get()
key = self.keyent.get()
def getTranslatedMessage(message, key):
tra = ''
for symbol in message:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupper():
if num > ord('Z'):
num -= 26
elif num < ord('A'):
num += 26
elif symbol.islower():
if num > ord('z'):
num -= 26
elif num < ord('a'):
num += 26
tra += chr(num)
else:
tra += symbol
def encrypt(self):
encryptedmessage = tra
self.messagetxt.delete(0.0, END)
self.messagetxt.insert(0.0, encryptedmessage)
root = Tk()
root.title("Encrypting message")
app = Application(root)
root.mainloop()
please could tell me whats wrong in this program and how to fix it?
By the way, i am only 12, and i am actually doing programming as a hobby. So i am planning to get better - i made a version of this code in normal(not GUI) python on my own and it worked - want to challenge myself and try to make it work in GUI.
Thank you

I copy/pasted your code and tried to compile it. That resulted in a large number of errors -- even after fixing the initial indentation errors. The main problem is that the variable tra is defined in function getTranslatedMessage() but you try to use it in encrypt(). It seems like you intended for both of those functions to be methods of the Application class; or something similar. Providing a good answer is difficult because your question has a large number of problems. So much so that I am inclined to suggest you do something else with your life than programming.

Related

binding return key in Python GUI

Working on a number guessing assignment for an informatics course and cannot for the life of me on this program bind this key. Using previous programs and class example I am able to bind this key to perform certain functions however not in this particular one. Therefore, I am assuming there is something super small wrong and im just overlooking it. Any help is appreciated.
from tkinter import *
import random
class Application(Frame):
def __init__(self, master): #sets up gui elements
Frame.__init__(self, master)
self.grid()
self.create_widgets()
self.number = random.randint(0, 9)
def create_widgets(self):
# creates instructions
Label(self, text = "I'm thinking of a number between 0 and 9.").grid(row = 0, column = 0, sticky = W)
Label(self, text = "Try and guess it!").grid(row = 1, column = 0, sticky = W)
# create guess label and entry
Label(self, text = "Your guess:").grid(row = 2, column = 0, sticky = W)
self.guess_ent = Entry(self)
self.guess_ent.grid(row = 2, column = 1, sticky = W)
# creates button to initiate run function
self.bttn=Button(self, text = "Submit", command = self.run)
self.bttn.grid(row = 3, column = 1, sticky = W)
#binds return key
self.bttn.bind('<KeyPress>', self.enter)
self.bttn.focus_set()
# creates feedback text box for run function
self.text = Text(self, width = 75, height = 10, wrap = WORD)
self.text.grid(row = 4, column = 0, columnspan = 4)
def run(self):
#gets random number
guess = int(self.guess_ent.get())
#if to test guesses and give appropriate feedback
if guess != self.number:
print_text = "You guessed {0}.".format(guess)
if guess > self.number:
print_text += " That's too high. Guess lower..."
elif guess < self.number:
print_text += " That's too low. Guess higher..."
self.text.delete(0.0, END)
self.text.insert(0.0, print_text)
self.guess_ent.delete(0, END)
else:
print_text = "That's the right number! You did it!!"
self.text.delete(0.0, END)
self.text.insert(0.0, print_text)
def enter(self, event):
if event.keysym == "Return":
self.run()
# main
root = Tk()
root.title("Number Guesser")
app = Application(root)
root.mainloop()
The return key in tkinter is also Return, hence your code should be :
self.bttn.bind('<Return>', self.enter)
You are binding the key to a button which does not get focus until pressed or tabbed into, making it almost impossible to notice the trigger of the binding, because your button and the bind call the same method.
Bind to the Entry widget such that you can trigger the binding while in the widget:
self.guess_ent.bind('<Return>', self.enter)

How to save counter of entries in str and show it in Text field?

Using such example i want to count number of entries. And represent string with number of entries in Text field. Like, for example:
1: number of entries(1)
21: number of entries(2)
...
Where should i put my counter variable?
import random
from tkinter import *
class MyApp(Frame):
def __init__(self, master):
super(MyApp, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
Label(self, text = 'Your number:').grid(row = 0, column = 0, sticky = W)
self.num_ent = Entry(self)
self.num_ent.grid(row = 0, column = 1, sticky = W)
Button(self, text = 'Check', command = self.update).grid(row = 0, column = 2, sticky = W)
self.user_text = Text(self, width = 50, height = 40, wrap = WORD)
self.user_text.grid(row = 2, column = 0, columnspan = 3)
def update(self):
guess = self.num_ent.get()
guess += '\n'
self.user_text.insert(0.0, guess)
root = Tk()
root.geometry('410x200')
root.title('Entries counter')
app = MyApp(root)
root.mainloop()
If I understand what you want correctly, simply keep count of the number of button presses, you can define a count variable in __init__ like
self.count = 0
And increase and print it in update like
def update(self):
self.count += 1
guess = self.num_ent.get()
guess += '\n'
self.user_text.insert(0.0, 'Guess #{}: {}'.format(self.count, guess))
It seems you're using Python 3.
The easiest way to store your counter is to use a dictionary. The key would be the text you're counting (1 and 21 according to your example), the value stores the count itself (e.g. 1 and 2).
The structured data for your example would look like this:
{
'1': 1,
'21': 2
}
And the final code:
from tkinter import *
class MyApp(Frame):
def __init__(self, master):
super(MyApp, self).__init__(master)
#this is your counter variable
self.entries = {}
self.grid()
self.create_widgets()
def create_widgets(self):
Label(self, text = 'Your number:').grid(row = 0, column = 0, sticky = W)
self.num_ent = Entry(self)
self.num_ent.grid(row = 0, column = 1, sticky = W)
Button(self, text = 'Check', command = self.update).grid(row = 0, column = 2, sticky = W)
self.user_text = Text(self, width = 50, height = 40, wrap = WORD)
self.user_text.grid(row = 2, column = 0, columnspan = 3)
def update(self):
#get the new entry from the text field and strip whitespaces
new_entry = self.num_ent.get().strip()
#check if the entry is already in the counter variable
if new_entry in self.entries:
#if it is: increment the counter
self.entries[new_entry] += 1
else:
#if it's not: add it and set its counter to 1
self.entries[new_entry] = 1
#delete the whole text area
self.user_text.delete('0.0', END)
#get every entry from the counter variable, sorted alphabetically
for key in sorted(self.entries):
#insert the entry at the end of the text area
self.user_text.insert(END, '{}: number of entries({})\n'.format(key, self.entries[key]))
root = Tk()
root.geometry('410x200')
root.title('Entries counter')
app = MyApp(root)
root.mainloop()

Tkinter - Python 3 - Adding an Increment Counter into a class window?

class AppetiserClass():
root = Tk()
root.title("Appetiser Page")
root.geometry("1920x1080")
meal1 = 0
def plus1():
global meal1
meal1 = meal1 + 1
DisplayButton["text"]=str(meal1)
return
def neg1():
global meal1
meal1 = meal1 + 1
DisplayButton["text"]=str(meal1)
return
app = Frame(root)
app.grid()
Label(app, text = "", width = 75, height = 20).grid(row = 1, column = 0, sticky = N)
DisplayButton = Button(app, text = meal1)
DisplayButton.grid(column = 1, row = 2, sticky = W)
DisplayButton.config(height = 10, width = 10 )
Plus1Button = Button(app, text = "+1", command=plus1, bg="green")
Plus1Button.grid(column = 2, row = 2, sticky = W)
Plus1Button.config(height = 10, width = 10 )
Neg1Button = Button(app, text = "-1", command=neg1, bg="green")
Neg1Button.grid(column = 3, row = 2, sticky = W)
Neg1Button.config(height = 10, width = 10 )
root.mainloop()
The problem I am having is that I have set a value to my global variable (meal1, being 0) but when I press the +1, or -1 button, a value is not being displayed on the "DislpayButton" and I am receiving this message:
"NameError: global name 'DisplayButton' is not defined "
"DisplayButton", is a button i have placed, to display a value onto. Nothing more, but I am receiving this error message.
If i remove the classes, and just run this code, with the single window, The code works fine.
Any help would be much appreciated!
If your indentation is correct, the problem isn't that DisplayButton and meal1 are global, it's that they're class-level and you're not accessing it that way, which means you should use self keyword to access it. (It doesn't have to be "self" - the first argument of any function in a class always defines the variable through which you can access other members in the same class - but it's Python style to use "self.") Add self as an argument to all your functions in that class, like so:
def neg1(self):
And then access meal1 and DisplayButton through self:
self.meal1 += 1
and:
self.DisplayButton["text"] = str(meal1)
I've re-written your class so that all the important stuff within the class can be accessed by everything else using self:
from tkinter import *
class AppetiserClass:
meal1 = 0
root = Tk()
app = Frame(self.root)
def __init__(self):
self.root.title("Appetiser Page")
self.root.geometry("1920x1080")
self.app.grid()
Label(self.app, text = "", width = 75, height = 20).grid(row = 1, column = 0, sticky = N)
self.DisplayButton = Button(self.app, text = self.meal1)
self.DisplayButton.grid(column = 1, row = 2, sticky = W)
self.DisplayButton.config(height = 10, width = 10 )
self.Plus1Button = Button(self.app, text = "+1", command=self.plus1, bg="green")
self.Plus1Button.grid(column = 2, row = 2, sticky = W)
self.Plus1Button.config(height = 10, width = 10 )
self.Neg1Button = Button(self.app, text = "-1", command=self.neg1, bg="green")
self.Neg1Button.grid(column = 3, row = 2, sticky = W)
self.Neg1Button.config(height = 10, width = 10 )
self.root.mainloop()
def plus1(self):
self.meal1 += 1
self.DisplayButton["text"]=str(self.meal1)
def neg1(self):
self.meal1 -= 1
self.DisplayButton["text"]=str(self.meal1)
if __name__ == "__main__":
AppetiserClass()
I changed a decent amount. First off, you had a lot of code written outside any particular method, which is something I prefer to keep inside the class methods except for class variable definitions (meal1 = 0 and etc.). It's fairly arbitrary - anything defined within a method as self.whatever has the same accessibility as stuff defined at the class scope. I've also made it so that you can keep reference to your buttons with self.ButtonName. Lastly, I've made it so that the window is instantiated only if you're running the file and not importing your code into a different file.

Python Code Error with Tkinter?

When I try to run the code it gives me this nasty error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__
return self.func(*args)
File "E:\Tkinter\count_num_CHALLENGE.py", line 39, in count_num
for num in range(start, end):
TypeError: 'Entry' object cannot be interpreted as an integer
Please help I don't know what is wrong! I tried int() Around entry but that did not work either If you guys can help me out that would be great. As I am in need of assistance
from tkinter import *
class Application(Frame):
def __init__(self, master):
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
# Create the instruction Label
Label(self,
text = "Enter a starting number then an ending number."
).grid(row = 0, column = 0, sticky = W)
# Create the entry box for starting/ending
self.starting_num = Entry(self)
self.starting_num.grid(row = 2, column = 0, sticky = W)
self.ending_num = Entry(self)
self.ending_num.grid(row = 3, column = 0, sticky = W)
# Create the text box
self.result_txt = Text(self, width = 20, height = 10, wrap = WORD)
self.result_txt.grid(row = 4, column = 0, columnspan = 1)
# Submit button
Button(self,
text = "Count the numbers",
command = self.count_num
).grid(row = 5, column = 0, sticky = W)
def count_num(self):
start = self.starting_num
end = self.ending_num
for num in range(start, end):
print(num)
self.result_txt.delete(0.0, END)
self.result_txt.insert(0.0, count_num)
# Main
root = Tk()
root.title("Count the numbers")
app = Application(root)
root.mainloop()
In your code, self.starting_num is an instance of an Entry widget, but you are trying to use it as if it were a number just as the error message is telling you.
I'm going to guess your intent is to use the value of the entry widget, in which case you need to use something like start=int(self.starting_num.get()), though you will need to handle the case where the entry is emply or has non-digits in it. The same goes for ending_num

Debugging RadioButtons program in Python

from Tkinter import *
class Application (Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.create_widgets()
def create_widgets(self):
Label(self, text = "Select the last book you read.").grid (row = 0, column = 0, sticky = W)
self.choice = StringVar()
Radiobutton (self,text = "Nausea by Jean-Paul Sartre",variable = self.choice,
value = "Wake up. This is a dream. This is all only a test of the emergency broadcasting system.",
command = self.update_text).grid (row = 2, column = 1, sticky = W)
Radiobutton (self,
text = "Infinite Jest by David Foster Wallace",
variable = self.choice,
value = "Because an adult borne without the volition to choose the thoughts that he thinks, is going to get hosed ;)",
command = self.update_text).grid (row = 3, column = 1, sticky = W)
Radiobutton (self,
text = "Cat's Cradle by Kurt Vonnegut",
variable = self.choice,
value = " \"Here we are, trapped in the amber of the moment. There is no why!\" ",
command = self.update_text.grid (row = 4, column = 1, sticky = W)
self.txt_display = Text (self, width = 40, height = 5, wrap = WORD)
self.txt_display.grid (row = 6, column = 0, sticky = W)
#There is only one choice value - self.choice. That can be "printed."
def update_text(self):
message = self.choice.get()
self.txt_display.delete (0.0, END)
self.txt_display.insert (0.0, message)
# The Main
root = Tk()
root.title ("The Book Critic One")
root.geometry ("400x400")
app = Application (root)
root.mainloop()
I keep getting a Syntax Error in the self.text_display_delete line which I can't seem to lose.
Any input would be greatly appreciated.
Take a look at the previous line - I only count one closing parenthesis, while you should have two:
Radiobutton (self,
text = "Cat's Cradle by Kurt Vonnegut",
variable = self.choice,
value = " \"Here we are, trapped in the amber of the moment. There is no why!\" ",
command = self.update_text.grid (row = 4, column = 1, sticky = W)) #<-- Missing that second paren
Usually if one line looks clean, the syntax error is on the previous line(s), and 99% of the time it's a missing paren.

Categories

Resources