from tkinter import *
import random
root = Tk()
name = StringVar()
class Window(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.master.title("Are you smart enough?")
self.pack(fill=BOTH, expand="no")
self.entry = Entry(root,textvariable=name)
self.entry.pack()
enterButton = Button(self, text="Enter", command=self.client_enter)
enterButton.pack(side="top", fill="none", expand="True", anchor = "s")
def client_enter(self):
text = name.get()
textlabel = Label(self, text=name).pack()
app = Window(root)
root.geometry("1200x600")
root.mainloop()
For some reason, when I input a name and press the "Enter" button, nothing shows up.
How can I make it say ("Welcome", name) on Tkinter?
It seems like the variable text contains the right value, but you are displaying the name (which is a StringVar) instead.
Replace this:
textlabel = Label(self, text=name).pack()
By this:
textlabel = Label(self, text=text).pack()
To make it say "Welcome, name", change the definition of text as such:
text = "Welcome, {}".format(name.get())
Also, textlabel becomes useless if you put .pack() in its definition. You should be doing it like this:
textlabel = Label(self, text=text)
textlabel.pack()
Or like this if you don't need to store it in a variable:
Label(self, text=text).pack()
Related
Learning to use Tkinter and following an online tutorial. This is an example given where text is entered and then label will update accordingly to the input text field.
I'm trying it in Python3 on Mac and on Raspberry Pi and I don't see the effect of trace, hence the label doesn't get modified by the Entry. Any help would be appreciate (or any other simple example of how to use Entry and Trace together)
Thanks.
from tkinter import *
class HelloWorld:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.button = Button(
frame, text="Hello", command=self.button_pressed
)
self.button.pack(side=LEFT, padx=5)
self.label = Label(frame, text="This is a label")
self.label.pack()
a_var = StringVar()
a_var.trace("w", self.var_changed)
self.entry = Entry(frame,textvariable=a_var)
self.entry.pack()
def button_pressed(self):
self.label.config(text="I've been pressed!")
def var_changed(self, a, b, c):
self.label.config(text=self.entry.get())
def main():
root = Tk()
root.geometry("250x150+300+300")
ex = HelloWorld(root)
root.mainloop()
if __name__ == '__main__':
main()
The problem is that you are using a local variable for a_var, and on the Mac it is getting garbage-collected. Save a reference to the variable (eg: self.a_var rather than just a_var).
self.a_var = StringVar()
self.a_var.trace("w", self.var_changed)
self.entry = Entry(frame,textvariable=self.a_var)
self.entry.pack()
Note: if all you want is to keep a label and entry in sync, you don't need to use a trace. You can link them by giving them both the same textvariable:
self.entry = Entry(frame, textvariable=self.a_var)
self.label = Label(frame, textvariable=self.a_var)
from tkinter import *
#Making the frame_____________
class Window(Frame):
def __init__(self, master = None):
Frame.__init__(self,master)
self.master = master
self.init_window()
#_____________________________
#Making the actual window
def init_window(self):
self.master.title("Ethics and similar topics quiz")#Title along the top of the window
self.pack(fill=BOTH, expand=1)
StartButton = Button(self, text="Start Quiz", fg = "Purple", command=self.showtxt)
StartButton.config(height = 4 , width = 25)
StartButton.place(x=815, y=1)#Positions it
def showtxt(self):
text1 = Label(self, text= "What is the meaning of the word 'Ethical'?")
text1.pack
There is my code, for some reason when I add anything else past the start button, it doesn't show up on my window. What's the issue?
You need to use text1.pack() rather than text1.pack. See here for an explanation of the pack() function.
I am trying to create a GUI for an auto-complete prototype and am new to tkinter. I want to get the entire input when Space is pressed but I am unable to do so. The idea is to get all the entries in the text box so that I can do some analysis inside a function call.
This is the code:
def kp(event):
app.create_widgets(1)
import random
def getFromScript(text):
#########THIS IS A PLACE HOLDER FOR ACTUAL IMPLEMENTATION
i= random.randint(1,100)
return ['hello'+str(i),'helou'+text]
from tkinter import *
class Application(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.create_widgets(0)
# Create main GUI window
def create_widgets(self,i):
self.search_var = StringVar()
self.search_var.trace("w", lambda name, index, mode: self.update_list(i))
self.lbox = Listbox(self, width=45, height=15)
if i==0:
self.entry = Entry(self, textvariable=self.search_var, width=13)
self.entry.grid(row=0, column=0, padx=10, pady=3)
self.lbox.grid(row=1, column=0, padx=10, pady=3)
# Function for updating the list/doing the search.
# It needs to be called here to populate the listbox.
self.update_list(i)
def update_list(self,i):
search_term = self.search_var.get()#### THIS LINE SHOULD READ THE TEXT
# Just a generic list to populate the listbox
if(i==0):
lbox_list = ['Excellent','Very Good','Shabby', 'Unpolite']
if(i==1):
lbox_list = getFromScript(search_term)####### PASS TEXT HERE
self.lbox.delete(0, END)
for item in lbox_list:
if search_term.lower() in item.lower():
self.lbox.insert(END, item)
root = Tk()
root.title('Filter Listbox Test')
root.bind_all('<space>', kp)
app = Application(master=root)
app.mainloop()
Any kind of help is highly appreciable. Thanks in advance
Problem is you are creating a new StringVar on each create_widgets call.
Create StringVar in your __init__.
class Application(Frame):
def __init__(self, master=None):
...
self.search_var = StringVar()
...
I'm trying to insert text into a textbox using Tkinter. I'm trying to insert information retrieved from a file but I've boiled it down to something simpler which exhibits the same problem:
class Main(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.init_ui()
def helloCallBack(self):
self.txt.insert("lol")
def init_ui(self):
self.txt = Text(root, width=24, height = 10).grid(column=0, row = 0)
load_button = Button(root, text="Load Wave Data", command = self.helloCallBack).grid(column=1, row = 0, sticky="E")
def main():
ex = Main(root)
root.geometry("300x250+300+300")
root.mainloop()
What I want it to do is whenever I press the button it inserts lol into the text box but I get the error
AttributeError: 'NoneType' object has no attribute 'insert'
How do I fix this?
You need to call grid in separated line. Because the method return None; causing the self.txt to reference None instead of Text widget object.
def init_ui(self):
self.txt = Text(root, width=24, height=10)
self.txt.grid(column=0, row=0)
load_button = Button(root, text="Load Wave Data", command=self.helloCallBack)
load_button.grid(column=1, row=0, sticky="E")
You need to specify where to insert the text.
def helloCallBack(self):
self.txt.insert(END, "lol")
To insert you need to indicate where you want to start inserting text:
self.txt.insert(0, "lol")
I'm making a program using Tkinter where the user inputs their weight in Pound and then it outputs their weight in kilo.
I'm having problems getting the contents of the Entry from the user.
I'm calculating the pound to kilo in clicked1.
Can someone show me how I would get the Entry input there?
from Tkinter import *
import tkMessageBox
class App(object):
def __init__(self):
self.root = Tk()
self.root.wm_title("Question 7")
self.label = Label (self.root, text= "Enter your weight in pounds.")
self.label.pack()
self.entrytext = StringVar()
Entry(self.root, textvariable=self.entrytext).pack()
self.buttontext = StringVar()
self.buttontext.set("Calculate")
Button(self.root, textvariable=self.buttontext, command=self.clicked1).pack()
self.label = Label (self.root, text="")
self.label.pack()
self.root.mainloop()
def clicked1(self):
input = 3423 #I would like the user input here.
self.label.configure(text=input)
def button_click(self, e):
pass
App()
What you are looking for is [widget].get()
Text widget
In case you use the Text widget, you have to use [widget].get(1.0, END) where 1.0 means "first line, 0th character"
Code review
I've noticed a few other things in your code that could get improved:
PEP8 conformity; see pep8online.com
If you add a Shebang, Linux users will be able to execute it directly with ./script.py.
Variable naming:
input is a built-in function and you should avoid overwriting it
Use meaningful variable names (entrytext might be problematic in case you extend your program)
Avoid from Tkinter import *. This might lead to unexpected naming clashes.
Complete code
##!/usr/bin/env python
import Tkinter as Tk
class App(object):
def __init__(self):
self.root = Tk.Tk()
self.root.wm_title("Question 7")
self.label = Tk.Label(self.root, text="Enter your weight in pounds.")
self.label.pack()
self.weight_in_kg = Tk.StringVar()
Tk.Entry(self.root, textvariable=self.weight_in_kg).pack()
self.buttontext = Tk.StringVar()
self.buttontext.set("Calculate")
Tk.Button(self.root,
textvariable=self.buttontext,
command=self.clicked1).pack()
self.label = Tk.Label(self.root, text="")
self.label.pack()
self.root.mainloop()
def clicked1(self):
weight_in_kg = self.weight_in_kg.get()
self.label.configure(text=weight_in_kg)
def button_click(self, e):
pass
App()
Is this the kinda thing you are looking for?
from Tkinter import *
import tkMessageBox
class App(object):
def __init__(self):
self.root = Tk()
self.root.wm_title("Question 7")
self.label = Label (self.root, text= "Enter your weight in pounds.")
self.label.pack()
self.entrytext = StringVar()
Entry(self.root, textvariable=self.entrytext).pack()
self.buttontext = StringVar()
self.buttontext.set("Calculate")
Button(self.root, textvariable=self.buttontext, command=self.clicked1).pack()
self.label = Label (self.root, text="")
self.label.pack()
self.root.mainloop()
def clicked1(self):
input = self.entrytext.get()
result = int(input)*2
self.label.configure(text=result)
def button_click(self, e):
pass
App()
I think this is what your'e looking for, although not just times by 2.
You would probably also want to put in an exception for if the value is not a int.
As you have associated a StringVar with your Entry widget, you can easily access/manipulate the widget's text with StringVar's get and set methods.
See here for more information.