Taking User Input. Python GUI - python-3.x

I'm in the process of making a python GUI calculator. I've been coding for no more than 3-4 week so my knowledge is limited. Anyway i want to make a pop up window that takes input from the user(Enter number, press a button to save that number in a variable).
That should be done twice(in order to add, subtract,... 2 numbers). Then i'll make another pop-up window saying: "The result is:(result)"
I know how to make an entry widget so my question is how do i make a button to save the user's input to a variable?

I highly recommend using a module called tkinter for new coders wanting to learn GUI programming in python. A complete tutorial can be found here:
http://zetcode.com/gui/tkinter/
However, creating a calculator with tkinter is pretty easy. Before you start you should think of what type of calculator you want to make, one with buttons or user input. Since you are a beginner let's do the user input method.
First if you cannot import tkinter without striking and error, head over to command prompt and write:
pip install tkinter
First things first we need to create the popup window:
from tkinter import *
window = Tk()
window.mainloop()
Now we need to create and Entry widget:
from tkinter import *
window = Tk()
User_input = Entry()
User_input.pack()
window.mainloop()
Now you will get an Entry where you will write your math problem.
Many people get confused at this stage because when they call the .get() function it doesn't work. This is because .get() makes a string. So in order to get an int you use
user_problem = int(User_input.get())
Then you use the int (numbers) the user wrote and solve them.
When using the button method assign a command callback to each button.

Related

root.deiconify(), trying to pick up a minimalized app. tkinter in python3

Part of the script responsible for minimalizing works just fine, point is, when I want to restore the window it doesnt work. I guess it's because the keyboard input is not sent into my app anymore. Can I fix that somehow? I use Ubuntu. How do I make the app wait for my shortcut no matter where in the system I am at the moment? I would like to make it work, even when I'm on my browser for example.
def minimize(event):
root.wm_state("iconic") # minimize the window
def restore_window(event):
root.deiconify()
root.bind("<Control-z>", minimize)
root.bind("<F11>", restore_window)
I dont know, maybe I should use a different package than tkinter for that kind of software.

Is there a way to get all keyboard input from turtle in python not just specific keys

Is there a way to get all keyboard input from turtle in python not just specific keys. I am aware I can use turtle.onkey(up, "Up") to call a function on a specific key press but I want to be able to get any key press without having to go through and manually set a function for every single key as I want to be able to display user text input in the turtle window directly without having to use console or alternatives like that.
the answer is no, you can't do it only with turtle, turtle built with tkinter and tkinter don't have that option, if you want to do it you should import other modules like pyinput, but pyinput may not that easy to learn (I didn't really try)
I just use the module "keyboard" (to download it on windows go to command prompt and type pip install keyboard) but I didn't try all of the functions with that module and I don't know if it is fully trusted, I just use it for one simple function which is
from keyboard import is_pressed as pressed
if keyboard.pressed('h'): # just for example it should be a string
# what ever you want to do here
so I really recommended to just learn pyinput cause it is really has more options, but if you don't use a lot of options you can do like me.

Nested functions inside a class in tkinter python [duplicate]

Consider below example:
import tkinter as tk
root = tk.Tk()
root.title("root")
other_window = tk.Tk()
other_window.title("other_window")
root.mainloop()
and also see below example that creates instances of Tk back-to-back instead of at once, so there's exactly one instance of Tk at any given time:
import tkinter as tk
def create_window(window_to_be_closed=None):
if window_to_be_closed:
window_to_be_closed.destroy()
window = tk.Tk()
tk.Button(window, text="Quit", command=lambda arg=window : create_window(arg)).pack()
window.mainloop()
create_window()
Why is it considered bad to have multiple instances of Tk?
Is the second snippet considered a bit better, or does it suffer from
the same conditions the first code does?
Why is it considered bad to have multiple instances of Tk?
Tkinter is just a python wrapper around an embedded Tcl interpreter that imports the Tk library. When you create a root window, you create an instance of a Tcl interpreter.
Each Tcl interpreter is an isolated sandbox. An object in one sandbox cannot interact with objects in another. The most common manifestation of that is that a StringVar created in one interpreter is not visible in another. The same goes for widgets -- you can't create widgets in one interpreter that has as a parent widget in another interpreter. Images are a third case: images created in one cannot be used in another.
From a technical standpoint, there's no reason why you can't have two instances of Tk at the same time. The recommendation against it is because there's rarely an actual need to have two or more distinct Tcl interpreters, and it causes problems that are hard for beginners to grasp.
Is the second snippet considered a bit better, or does it suffer from the same conditions the first code does?
It's impossible to say whether the second example in the question is better or not without knowing what you're trying to achieve. It probably is not any better since, again, there's rarely ever a time when you actually need two instances.
The best solution 99.9% of the time is to create exactly one instance of Tk that you use for the life of your program. If you need a second or subsequent window, create instances of Toplevel. Quite simply, that is how tkinter and the underlying Tcl/Tk interpreter was designed to be used.
I disagree with the tkinter community discouraging the use of multiple tk.Tk windows. You can have multiple tk.Tk windows. Using multiple instances of tk.Tk is the only way to create windows that are truly independent of each other. The only mistake most people make when creating multiple tk.Tk windows is that they forget to pass in master=... when creating PhotoImages/StringVars/IntVars/...
For example look at this code:
import tkinter as tk
root = tk.Tk()
root2 = tk.Tk()
variable = tk.StringVar() # Add `master=root2` to fix the problem
entry = tk.Entry(root2, textvariable=variable)
entry.bind("<Return>", lambda e: print(repr(variable.get())))
entry.pack()
root.mainloop()
The code above doesn't work. If you add master=root2 to the tk.StringVar(), then it will work perfectly fine. This is because tkinter stores the first instance of tk.Tk() in tk._default_root. Then if you don't pass in master=..., it will assume that you wanted the window in tk._default_root.
Another thing people get wrong is how many times should .mainloop() be called. It handles events from all tk.Tk windows that are alive so you only need one .mainloop().
For folks who disagree, I'd be interested in an example of where an actual problem is caused by the multiple tk.Tk windows.
The best reference I've found so far is the Application Windows section of the tkinterbook:
In the simple examples we’ve used this far, there’s only one window on the screen; the root window. This is automatically created when you call the Tk constructor
and
If you need to create additional windows, you can use the Toplevel widget. It simply creates a new window on the screen, a window that looks and behaves pretty much like the original root window
My take on it is that a Tk instance creates a Toplevel widget, plus things like the mainloop, of which there should be only one.
Tk() initializes the hidden tcl interpreter so that the code can run, as Tkinter is just a wrapper around tcl/tk. It also automatically creates a new window. Toplevel() just creates a new window, and wont work if Tk() hasn't been instantiated, as it requires the tcl interpreter that Tk() initializes. You cannot create any Tkinter widgets without instantiating Tk(), and Toplevel is merely a widget. In the question, you use Tk() to create a second window. You should instead create another file, because initializing the tcl interpreter multiple times can get confusing, as #Bryan Oakley explains so well. Then you should do:
from os import startfile
startfile(nameOfTheOtherFile)
, because, as Toplevel() is just a widget, it closes when the Tk() window is closed. Having the other window in a separate file makes it less confusing.

Simulate multiple click on a mouse press python

So I tried to simulate multiple mouse left click whenever I press the mouse's left button.However, my mouse start teleporting/moving slowly whenever I run my code. I am actually running this code with pycharm IDE.
I thought that maybe I am sending too much command per mouse press, so I decided to add a sleep between each click, to see the behavior. Unfortunately, the program still behave the same way.
from pynput.mouse import Listener,Controller, Button
import time
mouse = Controller()
def on_click(x, y, button, pressed):
if pressed and button == Button.left:
mouse.click(Button.right,2)
time.sleep(2)
print("stop")
with Listener( on_click=on_click) as listener:
listener.join()
I know that the code is not completed yet, but my final goal would be to simulate multiple click, with an interval of ~0.05 second, while I hold the mouse's left button.
Thank you,
Try using pyautogui rather than pynput.mouse.
Quick heads up I am not that good at python. Also, I know I am late because it's been over a year already but if this is not for you, it is also for future people who stumble upon this question/question in the future.
Before you look at the code and run it, we need to do one pip install.
In the console/terminal type
pip install pyautogui
In your case, you are using PyCharm. Just install the package pyautogui
Great! Now you are ready to look at the code:
import pyautogui
#You can change the clicks.
pyautogui.click(clicks=10)
For what you said about simulating an interval of 0.05 per second. I don't know how to help you there. Maybe try trial and error.
import pyautogui
seconds_for_clicking = 5
#This is for converting to actual seconds
seconds_for_clicking = seconds_for_clicking * 9
for i in range(seconds_for_clicking):
#You can change the clicks.
pyautogui.click(clicks=10)
#Maybe try this. In this case I think that you have to try trial and error. Change the number to whatever you want.
time.sleep(0.05)
``
Hope this helps :D

Python 3 & Tkinter buggy and slow

So, a few months back I made a small GUI for handling NPCs in a roleplaying campaign I was running. I haven't touched in since then, except that now I need it! Tomorrow, in fact...
I have a few odd error... Loading the GUI seems to work fine, but when I start to press buttons the troubles start. It seemed, at first, that it the script was very slow, which it shouldn't be, calling a two line dice function on a button press. I accidentally figured out that when I hover the mouse over the "close/minimize window" buttons (not in the GUI, but in the OS), the button would update with the result of the button press.
The same thing happens with a listbox I have: choosing an item may or may not select the item straight away (but hovering over the close/minimize updates it), and the results of the selection may or may not show. The results is in fact weirder: selecting a listbox item is supposed to get info from the selected item and print it in another frame. Even if the selection itself is fine without hovering, the printed text is somehow "clipped", showing only an area seeming to cover an arbitrarily sized square of text... Remedied by hovering, of course. The rest of the GUI have the exact same problems.
I have no clue what is going on here. The script was written on another computer, but that was also a Mac running the same OSX version (Mavericks), and it was a MUCH slower computer. This script shouldn't need any sort of advanced specs, though! I'm guessing it's something wrong with migrating to the new computer and the various version of different software? I'll paste the script down below, in case that'll help somehow.
Any help would be greatly appreciated, especially if it comes before the next epic campaign of Superheroes starts tomorrow afternoon! =P
[UPDATE]:
It was some time ago, but I still would like to have this problem solved. I've reduced my script to just a simple button, and the problem persists: clicking the button, even though there is no function or anything associated with it, only results in the frozen "button-clicked"-colour (i.e. light blue on OSX Yosemite), and I have to hover my mouse pointer over the close/minimize/etc. buttons in the top left corner to make it go back to "idle-button"-colour (i.e. grey).
#!/usr/bin/python
import tkinter as tk
root = tk.Tk()
test = tk.Button(root, text='test')
test.pack()
root.mainloop()
So, the problem obviously isn't with any of my "downstream" scripting, but something with the module or my way of calling it. Calling the script for the Terminal doesn't give me any error messages, and the problem is still there. Any ideas? It would be really, really good to get to the bottom of this problem!
I had the same problem when using Tk 8.5.13 on Mac OS X Sierra (10.12.3) with Python and IDLE v3.6.0.
Upgrading to TCL/Tk 8.5.18.0 as recommended on the Python Software Foundation page https://www.python.org/download/mac/tcltk/#activetcl-8-5-18-0 seemed to do the trick. This was the recommended version for my edition of the OS.
The interface I was building starting responding as I would expect, i.e. straight away when one of the controls was used. The only reservation I have so far is that normal buttons don't seem to have any sort of animation now, although the buttons do actually work.
-S.

Resources