So I have just a basic key/click logger for tkinter and I'm trying to display the log as a list to be printed out to the console however it doesn't seem to working at all. I used my terminal by compiling and writing "python logger.py" to try and get it to run and it runs but it prints nothing in the terminal. Then I copied and pasted my code towards PyCharm and it still doesn't seem to output it through the console there.
I pasted my code and was hoping if someone has any ideas on what could be wrong.
import tkinter as tkr
Log = []
master = tkr.Tk()
def char(event):
print("pressed", repr(event.char))
key1 = repr(event.char)
Log.append(key1)
print(Log)
def click(event):
frame.focus_set()
print("clicked", event.x,event.y)
key2 = event.x,event.y
Log.append(key2)
print(Log)
frame = tkr.Frame(master, height = 1000, width = 1000)
frame.bind("<Key>",char)
frame.bind("Button-1>",click)
frame.bind("Button-2>",click)
frame.bind("Button-3>",click)
frame.pack()
master.mainloop()
print(Log)
You have typo in "Button-1>", "Button-2>", "Button-3>".
You forgot < .
It has to be "<Button-1>", "<Button-2>", "<Button-3>"
EDIT: as said #razdi you need frame.focus_set() to get pressed key
frame.pack()
frame.focus_set()
Related
I'm just beginning to get the basic funtions of the soundcard python module to work. However I cannot make my tkinter window show up first and wait until I press the run button to exicute the "def run()" code. It always does the "def run()" code first and then opens the window. What am I doing wrong?
from tkinter import *
import soundcard as sc
window = Tk()
window.geometry("500x500")
window.title("Virtual Soundcard")
default_speaker = sc.default_speaker()
default_mic = sc.default_microphone()
def run():
with default_mic.recorder(samplerate=44100) as mic, \
default_speaker.player(samplerate=44100) as sp:
for val in range(100):
data = mic.record(numframes=None)
sp.play(data)
RunButton = Button(window, text ="Run", command = run())
RunButton.pack()
RunButton.place(x = 100, y = 250)
window.mainloop()
Change RunButton = Button(window, text ="Run", command = run()) to
RunButton = Button(window, text ="Run", command = run)
Basically remove the () for the command argument, with the () your calling the function even before pressing the button, ie, while code execution.
Hope this solved the error. Do let me know if any doubts or errors.
Cheers
I've started learning Tkinter(some of you may know why). So I made a simple program by following a tutorial:
from tkinter import *
root = Tk()
myLabel1 = Label(root, text = "Hello Mushroom world!")
myLabel2 = Label(root, text = "Hello Mario world!")
myLabel1.grid(row = 0, column = 0)
myLabel2.grid(row = 1, column = 0)
root.mainloop()
When I runed it, it showed me a blank window for less than a second and then it disappears (by the way, the window was as big as a restore down window but I think it was supposed to be small because I didn't specify the size of the window). I'm on Windows 10 using WSL2 and I run my code on command prompt because it's a GUI. I would like to know what is causing this bug. Thanks!
You can add a button that destroys the window, therefore quits the App.
from tkinter import *
root = Tk()
def close_window():
root.destroy()
myLabel1 = Label(root, text = "Hello Mushroom world!")
myLabel2 = Label(root, text = "Hello Mario world!")
button = Button (text = "Close", command = close_window)
myLabel1.grid(row = 0, column = 0)
myLabel2.grid(row = 1, column = 0)
button.grid(row = 2, column = 0)
root.mainloop()
You can simplify by instead of using the close_window function, just type root.destroy for the command parameter.
EDIT
After editing the original question, it turns out the OP's program quit after ~a second, and he wanted to know why does that happen, instead of another way to quit. The error seems to be in his environment. After changing to the original python IDE/IDLE, the code works fine.
Turns out he named his file tkinter.py, that caused the bug.
So I have this code:
try:
# for Python2
from Tkinter import *
except ImportError:
# for Python3
from tkinter import *
class Injector():
def __openInjector(self):
root = Tk()
root.geometry('600x400')
root.title('Toontown Rewritten Injector')
root.resizable(False, False)
def __init__(self):
self.code = ''
self.__openInjector()
def runInjectorCode(self):
exec(self.code.get(1.0, 'end'), globals())
def __openInjector(self):
root = Tk()
root.geometry('600x400')
root.title('Toontown Rewritten Injector')
root.resizable(False, False)
frame = Frame(root)
self.code = Text(frame, width=70, height=20)
self.code.pack(side='left')
Button(root, text='Inject!', command=self.runInjectorCode).pack()
scroll = Scrollbar(frame)
scroll.pack(fill='y', side='right')
scroll.config(command=self.code.yview)
self.code.config(yscrollcommand=scroll.set)
frame.pack(fill='y')
Injector()
In the IDLE console it works fine and does everthing I want it to do. But whenever I run the .py file on my Desktop. The black window appears, then just closes and nothing happens. Any help?
First, you have two methods in your class with the same name. The first one gets overwritten by the second one. At the end of that second one, you need the following line:
root.mainloop()
This will actually run the GUI. It's needed when running from a script, but not when running within the interactive interpreter.
Add it at the end of the second __openInjector:
...
self.code.config(yscrollcommand=scroll.set)
frame.pack(fill='y')
root.mainloop()
At the end of your second __openInjector method, add the line: root.mainloop().
This is necessary for Tkinter to run your code. mainloop is really nothing more than an infinite loop that waits for events. An event may be a user interaction, such as clicking a button.
My guess is you don't need mainloop when running interactively for purely convenience reasons.
I'm sure I'm doing something ridiculous, but I can't seem to figure out what it is. I've never programmed in Python before.
Anyway, I have a variable for my checkbox value, but the value of it doesn't change when clicking on the checkb. It always prints out 0. Any help would be greatly appreciated.
Running on Ubuntu 13.10 Python 2.7
program.py
from Tkinter import *
class Program:
def __init__(self):
top = Tk()
self.chk1Checked = BooleanVar()
chk1 = Checkbutton(top, text = "Testing", variable = self.chk1Checked)
chk1.pack()
btn1 = Button(top, text = "Click Me", command = self.btn1CallBack)
btn1.pack()
top.mainloop()
def btn1CallBack(self):
print self.chk1Checked.get()
if __name__ == "__main__":
Program()
It is a problem with my editor(IEP). When running from the command line everything works fine.
I was able to get it to work in IEP after changing my startup script to the program.py file. instead of just running the file itself. Not sure why this fixes it.
I'm using tkinter with Python to create a user interface for a program that converts Excel files to CSV.
I created a label to act as a status bar, and set statusBarText as a StringVar() as the textvariable. inputFileEntry and outputFileEntry are textvariables that contain the input and output file paths.
def convertButtonClick():
statusBarText.set('Converting...')
if inputFileEntry.get() == '' or outputFileEntry.get() == '':
statusBarText.set('Invalid Parameters.')
return
retcode = subprocess.('Program.exe' ,shell=true)
if retcode == 0:
statusBarText.set('Conversion Successful!')
else:
statusBarText.set('Conversion Failed!')
This function gets called when you click the convert button, and everything is working fine EXCEPT that the status bar never changes to say 'Converting...'.
The status bar text will get changed to invalid parameters if either the input or output are empty, and it will change to success or failure depending on the return code. The problem is it never changes to 'Converting...'
I've copied and pasted that exact line into the if statements and it works fine, but for some reason it just never changes before the subprocess runs when its at the top of the function. Any help would be greatly appreciated.
Since you're doing all of this in a single method call, the GUI never gets a chance to update before you start your sub process. Check out update_idletasks() call...
from http://infohost.nmt.edu/tcc/help/pubs/tkinter/universal.html
w.update_idletasks()
Some tasks in updating the display, such as resizing and redrawing widgets, are called idle tasks because they are usually deferred until the application has finished handling events and has gone back to the main loop to wait for new events.
If you want to force the display to be updated before the application next idles, call the w.update_idletasks() method on any widget.
How are you creating your Label?
I have this little test setup:
from Tkinter import *
class LabelTest:
def __init__(self, master):
self.test = StringVar()
self.button = Button(master, text="Change Label", command=self.change)
self.button.grid(row=0, column=0, sticky=W)
self.test.set("spam")
self.testlabel = Label(master, textvariable = self.test).grid(row = 0,column = 1)
def change(self):
self.test.set("eggs")
root = Tk()
root.title("Label tester")
calc = LabelTest(root)
root.mainloop()
And it works.
Did you make sure to use "textvariable = StatusBarText" instead of "text=StatusBarText.get()"?