Close and Open Another Window - python

I am trying to write a script that will ask a word in English and then show its meaning. I am able to ask the question but the answer window doesn't show up. Code I wrote so far as below. In second window, it starts like a new page. How can I modify it? Now, it shows the label but buttons doesn't seem.
from tkinter import *
class Application(Frame):
def __init__(self, master):
"""Initialize the Frame"""
Frame.__init__(self, master)
self.grid()
self.button_clicks = 0 # count the number of button clicks
self.create_widgets()
def root_close(self):
global root
root.destroy()
self.button_clicky()
def create_widgets(self):
"""Button displays number of clicks"""
if clicker % 2 == 0:
self.soru = Label(self, text="Kelime: " + kelime)
self.soru.grid(row=0, column=0, columnspan=2, sticky=W)
self.btn_submit = Button(self, text="Submit", command=self.root_close)
self.btn_submit.grid(row=3, column=1, sticky=W)
else:
self.cevap = Label(self, text="Kelimenin türkçe anlamları:\n" + anlam)
self.cevap.grid(row=0, column=0, columnspan=2, sticky=W)
self.btn_okay = Button(self, text="Bildim", command=self.dogru)
self.btn_submit.grid(row=3, column=0, sticky=W)
self.btn_okay = Button(self, text="Bilemedim", command=self.yanlis)
self.btn_submit.grid(row=3, column=2, sticky=W)
def button_clicky(self):
global clicker
clicker += 1
def dogru(self):
#will do stuff
self.root_close()
def yanlis(self):
self.root_close()
clicker = 0
kelime = "apple"
anlam = "elma"
root = Tk()
root.title("Ask word")
root.geometry("200x85")
app = Application(root)
root.mainloop()

So what I get from your question is that you have the first window with the Kelime question, and you want to open up another window with the else clause in your create_widgets() function once you click the submit button. The problem here is that when you are running root_close(), you're essentially terminating the whole program (the program runs because the root is on a loop created by root.mainLoop()). If you want to open one window when you close the other, check out Closing current window when opening another window
.

Related

Retrieve input from Entry widget stored as an instance variable and use it outside of the class

I have difficulties trying to get the input from Entry widget stored as a instance variable, so I can use it as input outside this class:
class CreateGUI:
def __init__(self, master):
self.master = master
self.master.geometry("275x325")
self.master.columnconfigure(0, weight=1)
self.master.columnconfigure(1, weight=2)
self.checkbutton_var1 = IntVar()
self.checkbutton_var2 = IntVar()
self.path = ''
self.type = []
def add_labels(self):
Label(self.master, text="Provide path to file:").grid(column=0, row=0, padx=10, pady=10, sticky="N")
def add_entries(self):
user_input = Entry(self.master)
user_input.grid(column=0, row=1, padx=5, pady=5, ipadx=60)
return user_input
def add_buttons(self, user_input):
checkbutton1 = Checkbutton(self.master, text="test1", variable=self.checkbutton_var1, onvalue=1,offvalue=0,height=2,width=10)
checkbutton1.grid(column=1, row=0)
checkbutton2 = Checkbutton(self.master, text="test2", variable=self.checkbutton_var2, onvalue=1, offvalue=0,height=2, width=10)
checkbutton2.grid(column=1, row=1)
button = Button(self.master, text="push", bg="pink", bd=100, fg="white",
command=lambda: self.retrieve_input(user_input.get(), self.checkbutton_var1.get(), self.checkbutton_var2.get()))
button.grid(column=0, row=3, padx=20, pady=20, sticky="NEWS")
def retrieve_input(self, p, *args):
self.path = p
#print(self.path)
for el in args:
self.type.append(el)
#print(self.type)
def main():
tk = Tk()
app = CreateGUI(tk)
app.add_labels()
user_input = app.add_entries()
app.add_buttons(user_input)
print(app.type)
print(app.path)
tk.mainloop()
When I start the program, write the input and press the button, it does not print anything. There are empty brackets printed the moment the program is initiated. The prints inside the retrieve_input are printing exactly what I need, but I need this inputs outside of the class, because they will be an input to another class.
I tried everything related to this problem, but it is not working and I would really appriciate any kind of help. Thanks!
You are getting the input for the Entry widget right before anyone can have a chance to type in it. As a result, user_input.get() will return an empty string. One thing you can do is make some sort of trigger for calling add_buttons() that the user activates when they are done filling out user_input. Further tweaking after that should make it work.
Please tell me if you have any more trouble.

Adding button (with variables) by pressing button - tkinter

I'm making a point of sale system and trying to implement a button, that when pressed a new button appears but also, a window which asks the user to input an Item
def newButton ():
w = Toplevel()
w.title("New Item") #creates new window when button is pressed
w.geometry("200x200")
itemNameLabel = Label(w, font=("arial", 15), text="What is the item called?")
itemNameLabel.grid(row=0, padx=5)
itemName = Entry(w, width=18, borderwidth=5)
itemName.grid(row=1, padx=5)
newItemName = itemName.get
itemPriceLabel = Label(w, font=("arial", 15), text="What is the item's price?")
itemPriceLabel.grid(row=4, padx=5)
itemPrice = Entry(w, width=18, borderwidth=5)
itemPrice.grid(row=5, padx=5)
def item6_Button():
global item6_qty
item6_price = itemPrice.get
item6_text = newItemName
item6_qty += 1
item6_text = (item6_text + " "+str(item6_price) +" "+ str(item6_qty)) #concatonates text & variable
item6.config(text=item6_text) #updates label text - doesn't add multiple
item6.pack()
item6_Button = Button(itemFrame, text=newItemName, width=10, height=5, command=item6_Button)
item6_Button.grid(row=7, column=1, padx=5)
item6 = Label(receiptFrame)
w.mainloop()
newButton= Button(itemFrame, text="Add New Button", width=20, height=5, command=newButton) #creates button for new window
newButton.place(x=480, y=600)
newButton = Label(itemFrame)
*item6_qty and item6_price are declared near the beginning of the program
This is what I have so far and although the window appears, I don't think the variables are actually set, on top of the new button appearing in the item frame. I'm not entirely sure how to go about this - do I need to use .insert for the variables?
This is the standard code I have which creates the normal button
#Item1 Button + Function
def item1_Button():
global item1_qty #making qty variable global so it can used
item1_text = ("Chips")
item1_qty += 1 #increments qty variable by one everytime button is clicked
item1_text = (item1_text + " "+str(item1_price) +" "+ str(item1_qty)) #concatonates text & variable
item1.config(text=item1_text) #updates label text - doesn't add multiple
item1.pack() #places label within the frame
item1_Button = Button(itemFrame, text="Chips", width=10, height=5, command=item1_Button)
#creates button + links to function
item1_Button.grid(row=4, column=1, padx=5) #positions button
item1 = Label(receiptFrame)#creates label for button
I'm not sure if I've provided enough code of what I've done to give a better picture of what I'm trying to achieve but I know large chunks of code aren't very favoured
here is an example of what You could do (does this help?):
from tkinter import Tk, Button, Entry, Toplevel
class MainWindow(Tk):
def __init__(self):
Tk.__init__(self)
self.geometry('100x150')
self.btn = Button(self, text='Create New!', command=self.ask)
self.btn.pack()
def ask(self):
ask_window = InputWindow(self)
ask_window.focus_force()
def create(self, text):
button = Button(self, text=text)
button.pack()
class InputWindow(Toplevel):
def __init__(self, parent):
Toplevel.__init__(self, parent)
self.parent = parent
self.bind('<FocusOut>', self.destroy_)
self.user_input = Entry(self)
self.user_input.pack()
self.submit_btn = Button(self, text='Submit!', command=self.retrieve)
self.submit_btn.pack()
def retrieve(self):
text = self.user_input.get()
self.parent.create(text)
self.destroy()
def destroy_(self, event):
if isinstance(event.widget, Toplevel):
self.destroy()
root = MainWindow()
root.mainloop()

How to make a tkinter button open only one Toplevel?

I need a tkinter button to open only one Toplevel
but I tried using a counter that changes to 2 when one Toplevel is made and a if loop so it checks if the counter is 1, (it will make a Toplevel window if its 1)
but when I run the program I can make many windows by clicking the button multiple times
I think the solution of using a counter doesn't work
def menu_window(self): # this is in a class
self.frame4 = tk.Frame(self.master, padx=30, pady=30)
self.frame4.grid()
Counter = 1 ### COUNTER
button2 = tk.Button(self.frame4, text="Review your Quiz", command=lambda: PreviewQuiz(self.master, self.frame4,
Counter))
button2.grid(row=3, column=2, padx=40, pady=15, ipadx=28)
button3 = tk.Button(self.frame4, text=" Start your Quiz ")
button3.grid(row=4, column=2, padx=40, pady=5, ipadx=30)
class PreviewQuiz:
def __init__(self, master, frame4, Counter):
if Counter == 1: # CHECK IF COUNTER IS 1
self.master = master
self.review_q = tk.Toplevel(self.master)
self.frame5 = tk.Frame(self.master, padx=50, pady=20)
self.frame5.grid()
self.Counter = 2 # SET COUNTER TO 2
Just disable the button when the user clicks on it and enable it only when the top-level is closed.
Here is an example taken from the code you provided in your newest post:
import tkinter as tk
class Run:
def __init__(self, master):
self.master = master
self.button = tk.Button(master, text="TopLevel", command=self.make_new)
self.button.pack()
def make_new(self):
self.button['state'] = 'disabled'
new = tk.Toplevel(self.master)
lbl = tk.Label(new, text='only one topLevel')
lbl.pack()
new.protocol("WM_DELETE_WINDOW", lambda : self.button.configure(state='normal') or new.destroy()) # or make a method to change the state
master1 = tk.Tk()
i = Run(master1)
master1.mainloop()
Your code does not run, which makes it difficult to debug. There are however a few things:
When you assingn a value to counter in menu_window() you end the value with a ".", which makes it a float, not an integer.
You call PreviewQuiz with the counter argument, but when you update the counter you do it to an instance variable of PreviewQuiz, not of menu_window() class so next time you call PreviewQuiz you will still use 1.0.

How Transfer cursor in tkinter?

i wrote bellow code in python 3.6.2 by tkinter,I want the cursor move to password textbox when user press Enter key in username textbox.
from tkinter import *
class Application(Frame):
def __init__(self,master):
super(Application, self).__init__(master)
self.grid()
self.create_main()
def create_main(self):
print("testing")
self.title = Label(self, text=" Stuck In The Circle ")
self.title.grid(row=0, column=2)
self.user_entry_label = Label(self, text="Username: ")
self.user_entry_label.grid(row=1, column=1)
self.user_entry = Entry(self)
self.user_entry.grid(row=1, column=2)
self.pass_entry_label = Label(self, text="Password: ")
self.pass_entry_label.grid(row=2, column=1)
self.pass_entry = Entry(self)
self.pass_entry.grid(row=2, column=2)
self.user_entry = Entry(self, justify="right")
self.pass_entry = Entry(self, justify="right")
self.sign_in_butt = Button(self, text="Sign In",command = self.logging_in)#SIGN IN BUTTON
self.sign_in_butt.grid(row=5, column=2)
def logging_in(self):
user_get = self.user_entry.get()
pass_get = self.pass_entry.get()
root = Tk()
root.title("Stuck in the Circle")
root.geometry("400x100")
app = Application(root)
root.mainloop()
How can do it?
This is actually a lot simpler than I expected it to be.
We can use .bind() to get a callback on the <Return> event. This means that every time the return character is pressed whenever the defined widget is in focus we get a callback.
In order to get it to cycle to the next widget we can use this answer from Bryan Oakley:
def focus_next_window(event):
event.widget.tk_focusNext().focus()
return("break")
text_widget=Text(...) text_widget.bind("<Tab>", focus_next_window)
Important points about this code:
The method tk_focusNext() returns the next widget in the keyboard
traversal hierarchy. the method focus() sets the focus to that widget
returning "break" is critical in that it prevents the class binding
from firing. It is this class binding that inserts the tab character,
which you don't want.
So, applying the same logic in our situation we can use something like the below:
from tkinter import *
class App:
def __init__(self, root):
self.root = root
self.entry1 = Entry(self.root)
self.entry2 = Entry(self.root)
self.entry1.pack()
self.entry2.pack()
self.entry1.bind("<Return>", self.callback)
def callback(self, event):
event.widget.tk_focusNext().focus()
root = Tk()
App(root)
root.mainloop()

Tkinter store entry box value as value for other file

This is my first python personal project. I am wanting to use Tkinter to create a window (GUARDIAN LOCATOR) that asks the user to input a value (enter sailor guardian) into the entry box. The rest of the program is dependent on what the user types in the entry box as I will be having if/else statements reacting to the sailor guardian entered.
The issue I am having is storing what is entered in the entry box as a variable to use in my main file for the if/else statements. I can get the value to print to the prompt window, but I haven't been able to store it successfully to a global variable.
My Tkinter window is in it's own class.
I have tried many different ways of doing this based on similar issues from stackoverflow, but I am getting an error every time. This is my base code that still produces the error.
Class file with the Tkinter window
class GuardianLocator:
def __init__(self, master):
frame = Frame(master)
frame.grid()
master.title("GUARDIAN LOCATOR")
self.locator_label = Label(frame, text="Which Sailor Guardian are you looking for?", width=40, height=2)
self.locator_label.grid()
self.entry = Entry(frame)
self.entry.grid()
self.button1 = Button(frame, text="Search", command=self.guardian_name, pady=2)
self.button1.grid()
def guardian_name(self):
print(self.entry.get())
and in my main working file
root = Tk()
locator = guardian_locator.GuardianLocator(root)
root.mainloop()
This is my test loop to see if it's working.
if locator.guardian_input() is "Sailor Moon":
print("hi")
else:
print("no")
Not sure exactly how your code is organized and where is your "test loop" located, but I assume it is after root.mainloop(). Thus the script can be as follows:
from tkinter import *
class GuardianLocator:
def __init__(self, master):
self._name = ""
frame = Frame(master)
frame.grid()
master.title("GUARDIAN LOCATOR")
self.locator_label = Label(frame, text="Which Sailor Guardian are you looking for?", width=40, height=2)
self.locator_label.grid()
self.entry = Entry(frame)
self.entry.grid()
self.button1 = Button(frame, text="Search", command=self.guardian_name, pady=2)
self.button1.grid()
def guardian_name(self):
self._name = self.entry.get()
print(self.entry.get())
root = Tk()
locator = GuardianLocator(root)
root.mainloop()
# this will be executed after the root window is closed.
print("Name is", locator._name)
Please note self._name = "" in the constructor. This instance variable can be used to store the name provided in your GuardianLocator window.

Categories

Resources