Lets say I have this code
import math
from tkinter import *
def close_window():
root.destroy()
def fileName():
filename = content.get()
return filename;
root = Tk()
content = StringVar()
L2 = Label(root, text = "The Program").grid(row = 0, sticky = E)
L1 = Label(root, text = "Enter filename").grid(row = 1, column = 0, sticky = E)
E1 = Entry(root, bd = 5, textvariable = content).grid(row = 1, column = 1)
B1 = Button(root, text = "Ok", command = fileName).grid(row = 2, column = 0 )
B2 = Button(root, text = "Quit", command = close_window).grid(row = 2, column = 1)
root.mainloop()
print(fileName())
Now the problem is I want to store the content I enter in E1 (so I later can do things to it) but how do I access it "outside" of the GUI?
The program I want to make is that the user enters a file name, then it runs a bunch of functions on the input and then produce a textmessage based on whats given, but I cant access the input since
fileName()
doesnt return anything.
Not sure if this does what you wanted but now it prints on button click and you have you filename variable set to content.get()
import math
from tkinter import *
def close_window():
root.destroy()
def fileName():
filename = content.get()
return filename;
def combine_funcs(*funcs):
def combined_func(*args, **kwargs):
for f in funcs:
f(*args, **kwargs)
return combined_func
def prnt():
print(content.get())
root = Tk()
content = StringVar()
L2 = Label(root, text = "The Program").grid(row = 0, sticky = E)
L1 = Label(root, text = "Enter filename").grid(row = 1, column = 0, sticky = E)
E1 = Entry(root, bd = 5, textvariable = content).grid(row = 1, column = 1)
B1 = Button(root, text = "Ok", command = combine_funcs(fileName,prnt)).grid(row = 2, column = 0 )
B2 = Button(root, text = "Quit", command = close_window).grid(row = 2, column = 1)
root.mainloop()
print(fileName())
Related
I'm trying to make a login window. I found a good example code here in Stackoverflow and added it with a simple code using Entry widget. After log in successfully, however, I can't get correct values of textvariable of Entry Widget even though I try to get them with Entry's instance.get().
I've tried many ways I could do. But, I can't find what's wrong.
I'm working with python 2.7. please help.
from Tkinter import *
import tkMessageBox as tm
class LoginFrame:
def __init__(self):
root = Tk()
self.label_1 = Label(root, text="Username")
self.label_2 = Label(root, text="Password")
self.entry_1 = Entry(root)
self.entry_2 = Entry(root, show="*")
self.label_1.grid(row=0, sticky=E)
self.label_2.grid(row=1, sticky=E)
self.entry_1.grid(row=0, column=1)
self.entry_2.grid(row=1, column=1)
self.checkbox = Checkbutton(root, text="Keep me logged in")
self.checkbox.grid(columnspan=2)
self.logbtn = Button(root, text="Login", command =
self._login_btn_clickked)
self.logbtn.grid(columnspan=2)
root.mainloop()
def _login_btn_clickked(self):
username = self.entry_1.get()
password = self.entry_2.get()
#print(username, password)
if username == "1" and password == "1":
#tm.showinfo("Login info", "Welcome John")
app = EntrySample()
app.window.mainloop()
else:
tm.showerror("Login error", "Incorrect username")
class EntrySample:
def __init__(self):
self.window = Tk()
self.window.title("Test Entry")
Label(self.window, text = "Kor").grid(row = 1,
column = 1, sticky = W)
self.kor = IntVar()
self.enKor = Entry(self.window, textvariable = self.kor,
justify = RIGHT).grid(row = 1, column = 2)
Label(self.window, text = "Eng").grid(row = 2,
column = 1, sticky = W)
self.eng = IntVar()
self.enEng = Entry(self.window, textvariable = self.eng,
justify = RIGHT).grid(row = 2, column = 2)
Label(self.window, text = "Math").grid(row = 3,
column = 1, sticky = W)
self.math = IntVar()
self.enMath = Entry(self.window, textvariable = self.math,
justify = RIGHT).grid(row = 3, column = 2)
btComputePayment = Button(self.window, text = "Calculate",
command = self.compute).grid(
row = 4, column = 2, sticky = E)
def compute(self):
total = self.kor.get()+self.eng.get()+self.math.get()
avg = total/3.0
print total
print '%3.2f' %avg
LoginFrame()
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.
When i run it the two buttons show up but when i press 'Log In', This error shows:
inputDialog2 = LogIn(root)
TypeError: LogIn() takes no arguments (1 given)
and if i press 'Register', This error shows:
self.Label1 = Label(top, text = "What is your username: ")
AttributeError: Label instance has no __call__ method
This is my code:
from Tkinter import *
# User Registers an account with a username password and passwor retype.
class Main:
def __init__(self, parent):
top = self.top = Toplevel(parent)
self.Label = Label(top, text = 'Choose an option')
self.Label.grid(row = 0)
self.LoginB = Button(top, text = 'Log In', command = LogIn)
self.LoginB.pack()
self.RegisterB = Button(top, text = 'Register', command = launch_register)
self.RegisterB.pack()
Main().pack()
class Register:
def __init__(self, parent):
top = self.top = Toplevel(parent)
self.VarEntUser = StringVar()
self.VarEntPass = StringVar()
self.VarEntRetype = StringVar()
self.Label1 = Label(top, text = "What is your username: ")
self.Label2 = Label(top, text = "Enter a password: ")
self.Label3 = Label(top, text = "Retype Password: ")
self.EntUser = Entry(top, textvariable = self.VarEntUser )
self.EntPass = Entry(top, textvariable = self.VarEntPass)
self.EntRetype = Entry(top, textvariable = self.VarEntRetype)
self.Label1.grid(row = 0, sticky = W)
self.Label2.grid(row = 1, sticky = W)
self.Label3.grid(row = 2, sticky = W)
self.EntUser.grid(row = 0, column = 1)
self.EntPass.grid(row = 1, column = 1)
self.EntRetype.grid(row = 2, column = 1)
self.MySubmitButton = Button(top, text = 'Submit', command=RegisterCheck)
self.MySubmitButton.pack()
self.U = raw_input(self.VarEntUser.get())
self.P = raw_input(self.VarEntPass.get())
self.R = raw_input(self.VarEntRetype.get())
class LogIn:
def __init__(self, parent):
top = self.top = Toplevel(parent)
VarUserLog = StringVar()
VarPassLog = StringVar()
self.LabelUser = Label(top, text = 'Username:')
self.EntUserLog = Label(top, text = 'Password: ')
self.EntUserLog = Entry(top, textvariable = self.VarUserLog)
self.EntPassLog = Entry(top, textvariable = self.VarPassLog)
self.UserLog.grid(row = 1)
self.PassLog.grid(row = 2)
self.EntUserLog.grid(row = 1, column = 1)
self.EntPassLog.grid(row = 2, column = 1)
# runs the 'LoginCheck' function
self.LogInButton = Button(top, text = "Log In", command = LogInCheck)
self.User = raw_input(self.EntUserLog.get())
self.Pass = raw_input(self.EntUserLog.get())
# Checks the Log In details
def LogInCheck():
if len(self.User) <= 0 and len(self.Pass) <= 0:
print "Please fill in all fields."
else:
pass
if self.User in 'username.txt' and self.Pass in 'password':
print 'You are now logged in!'
else:
print "Log in Failed"
# Checks the password and checks if all fields have been entered
def RegisterCheck(self):
if len(self.P) <= 0 and len(self.U) <= 0:
print "Please fill out all fields."
else:
pass
if self.P == self.R:
pass
else:
print "Passwords do not match"
with open('username.txt', 'a') as fout:
fout.write(self.U + '\n')
with open('password.txt', 'a') as fout:
fout.write(self.P + '\n')
def launch_register():
inputDialog = Register(root)
root.wait_window(inputDialog.top)
def LogIn():
inputDialog2 = LogIn(root)
root.wait_window(inputDialog2.top)
# Main Window--
root = Tk()
Label = Label(root, text = 'Choose an option')
Label.pack()
LoginB = Button(root, text = 'Log In', command = LogIn)
LoginB.pack()
RegisterB = Button(root, text = 'Register', command = launch_register)
RegisterB.pack()
root.mainloop()
The mistakes in your program that cause these errors:
You start by declaring a class named LogIn; however you later create a function with the same name. Since the latter overrides the former, your method is called instead of your class constructor.
Similarly, in the line Label = Label(root, text = 'Choose an option') you assign a new meaning to the name Label, such that when you get to the line on which the second error occurs, the name Label does no longer refer to a class named Label, but instead an instance of that class.
Basically, you should use unique names for your variables, functions and classes (including names you import from modules such as Tkinter).
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()
Trying to make a very basic addition calculator with python and tkinter. It gives me an error:
btresult = Button(window, text = "Compute Sum", command = self.result).grid(row = 4, column = 2, sticky = E)
^
SyntaxError: invalid syntax
I am having trouble figuring out how to connect this.
from tkinter import *
class addCalculator:
def __init__(self):
window = Tk()
window.title("Add Calculator")
Label(window, text = "First Number: ").grid(row = 1, column = 1, sticky = W)
Label(window, text = "Second Number: ").grid(row = 2, column = 1, sticky = W)
self.number1Var = StringVar()
Entry(window, textvariable = self.number1Var, justify = RIGHT).grid(row = 1, column = 2)
self.number2Var = StringVar()
Entry(window, textvariable = self.number2Var, justify = RIGHT).grid(row = 2, column = 2)
self.resultVar = StringVar()
lblresult = Label(window, textvariable = self.result.grid(row = 3, column = 2, sticky = E)
btresult = Button(window, text = "Compute Sum", command = self.result).grid(row = 4, column = 2, sticky = E)
def result(self):
resultVar = self.resultVar.set(eval(self.number1Var.get()) + eval(self.number2Var.get()))
return resultVar
window.mainloop()
addCalculator()
On the previous line (lblresult = ...), you forgot to close your opened parentheses. Python interprets this (both that line and the next line, btresult = ...) as one whole line of code, but obviously this can't work with your code, hence the SyntaxError
I solved this problem in my own way. I tried to stay faithful to the original question but the code needed a lot of clean up. There was lots of little odds and ends to fix, but i think the main problem was the method of passing the integers to the function. I also changed the original lblresult from a label to an Entry widget. Im still new at Python but getting better. I found this question while looking for a similar answer and solving this also solved my problem. Thanks! Code below:
from Tkinter import *
class addCalculator:
def __init__(self):
window = Tk()
window.title("Add Calculator")
def result(z1,z2):
biz=z1+z2
lblresult.delete(0,END)
lblresult.insert(0,biz)
return
Label1 = Label(window, text = "First Number: ").grid(row = 1, column = 1, sticky = W)
Label2 = Label(window, text = "Second Number: ").grid(row = 2, column = 1, sticky = W)
self.number1Var = IntVar()
Entry1 = Entry(window, textvariable = self.number1Var, justify = RIGHT).grid(row = 1, column = 2)
self.number2Var = IntVar()
Entry2 = Entry(window, textvariable = self.number2Var, justify = RIGHT).grid(row = 2, column = 2)
Label3 = Label(window, text = "Result: ").grid(row = 3, column = 1, sticky = W)
lblresult = Entry(window, justify = RIGHT)
lblresult.grid(row = 3, column = 2, sticky = E)
btresult = Button(window,text="Compute Sum",command=lambda:result(self.number1Var.get(),self.number2Var.get()))
btresult.grid(row = 4, column = 2, sticky = E)
window.mainloop()
addCalculator()