tkinter in IDLE vs spyder - python

I keep on encountering problems with Tkinter in spyder and I am unsure why. Repeatedly I'd spent a lot of time trying to fix code in spyder which is fully operational in IDLE. Is there a simple reason for this? Is my code wrong and IDLE is ignoring the incorrect bits while spyder is having an issue. When running the code there is never an error in spyder it just doesn't operate as expected. I will show some code that displays differently in IDLE than it does spyder.
from tkinter import font
import tkinter as tk
root = tk.Tk()
root.title("N Body Simulation")
root.geometry('400x300')
frame = tk.Frame(root)
frame.pack()
# titlefont = font.Font(family="Lucida Grande",size=45)
titlefont = font.Font(family='Helvetica', name='titlefont', size=50, weight='bold')
text_intro = "N-Body Simulation"
title = tk.Label(root, text=text_intro, font=titlefont)
title.place(relx=0.5, rely=0.1, anchor="center")
root.mainloop()
The image on the top is from spyder and the one on the bottom is IDLE. Why does it keep appearing different, and what am I doing wrong. To me, I have done the necessary steps to change the font size and make it bold. Also is there a way to run it like IDLE but though spyder, sorry if that last part is a silly question. Thanks in advance.

Related

Windows with tkinter

I started studying Python last Monday. I tried to create a window using tkinter. Pycharm says there are no mistakes but after running the code the window doesn't appear D:
That's my code
from tkinter import *
window = Tk()
window.title("thecharmii")
window.geometry("700x500")
window.config(background = "black")
window.mainloop()
I downloaded the latest Python version, I guess it's 3.10. When I click on Run the window doesn't appear but it looks like the process is still running. Thanks for the help
try this
from tkinter import *
def main():
window = Tk()
window.title("thecharmii")
window.geometry("700x500")
window.config(background = "black")
window.mainloop()
main()
It works completely fine with me.
Try running it in your cmd/powershell/terminal.
If it is running, then it might be that the configurations for the file you are working with in pycharm are messed up.

Tkinter canvas doesn't show

I'm new to Tkinter, Python and Linux. I'm running Ubuntu 19.04 and trying to run my Python-Tkinter code in Atom, but when I run it, only terminal shows up with an information about successful execution and execution time. No canvas appears.
import tkinter
canvas = tkinter.Canvas(width=200, height=200, bg="white")
canvas.pack()
canvas.create_line(0,0,100,100)
I expect new window with canvas and line to appear, but that doesn't happen, I only get terminal saying:
Process returned 0 (0x0) execution time : 0.307 s
Press [ENTER] to continue...
Thank you for your help.
Like PRMoureu and furas said, I only added canvas.mainloop() at the end and that solved my problem! Thank them!
import tkinter
canvas = tkinter.Canvas(width=200, height=200, bg="white")
canvas.pack()
canvas.create_line(0,0,100,100)
canvas.mainloop()

root.overrideredirect and <Any-KeyPress> binding

I would like the following program to quit on <Any-KeyPress> event.
from tkinter import *
root = Tk()
root.overrideredirect(True)
root.bind('<Any-KeyPress>', lambda e: root.destroy())
root.mainloop()
This works fine on Windows OS. However this does not work on Ubuntu unless I remove the line root.overrideredirect(True) from the above code.
Is this the intended behavior ?
Or is there a way whereby I can make my program to work while still using root.overrideredirect(True) ?
Edit
I just saw a similar question here at SO, where Bryan Oakley suggests using root.focus_force() but it does not help.
Edit 2
I used root.attributes('-fullscreen', True) instead of root.overrideredirect(True) as suggested here and that seems to work now.
Try this:
from tkinter import *
root = Tk()
root.bind('<Any-KeyPress>', quit())
root.mainloop()
Assuming that you want the program to quit, keep the code. If you just want to clear the screen, just use root.destroy() rather that quit(). Using root.overrideredirect(True) will NOT work on Ubuntu.

Python Tkinter not working in a .py file

My problem is that my python code is not working when I run it as a .py file. Here is the code:
import tkinter
tk=tkinter.Tk()
canvas=tkinter.Canvas(tk, width=500, height=500)
canvas.pack()
There is more code to it than that, but that is the relevant stuff. It works fine when I use the python shell or type it directly into the python console, but when I run it as a .py file, it seems to skip this code and go on to the rest, without displaying a canvas. I am using windows, but I am not sure what version of python I'm using.
I was also using
from * import tkinter
before, with relevant changes to the code and i changed it to try and help fix it. It didn't work :(
You are missing the eventloop at the end:
import tkinter
tk=tkinter.Tk()
canvas=tkinter.Canvas(tk, width=500, height=500)
canvas.pack()
# Enter into eventloop <- this will keep
# running your application, until you exit
tk.mainloop()
Only a personal recommendation: don't use tk as a variable name, use app or root or even win/window

Python Tkinter Flashing Standard Window

I am building an Interface with TKinter and I have the problem, that whenever create a new window the standardized tkinter window of 200x200 pixel with nothing in it flashes up for a fraction of a second and AFTER that all my modifications (widgets ect.) are made. This happens before AND after calling the mainloop.
The Main-Interface is created.
Mainloop stats
Flashing window
Main-Interface appears
Also after Mainloop was called this happens with newly created windows.
Main-Interface appears--> Push a button, that creates a new window
Flashing window
new window appears
Sadly I cannot give you a sample code... If I try to do a minimal example, this doesn't happen. Maybe the standard window is created, but it is changed so fast, that it doesn't appear on screen. I don't even know what to look up in this case... searching "tkinter flashing window" yields nothing.
EDIT: I found the source of the problem. It seems to be caused by wm_iconbitmap, FigureCanvasTkAgg and tkinter.Toplevel. If you remove the the icon out of the code, it works fine, no flashing. But if I use it together with one of the other, the window flashes when created. Try it out with the code below. You have to put the icon in the working directory of course.
Here is a code sample and the link to the icon I am using, but I suppose any icon will do.
# coding=utf-8
import numpy as np
import matplotlib as mpl
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
import os
class INTERFACE(object):
def __init__(self):
self.root = tk.Tk()
self.root.protocol("WM_DELETE_WINDOW", self.EXIT)
self.root.wm_iconbitmap( os.path.abspath("icon.ico")) #<---- !!!!!!
self.root.geometry("1024x768")
canvas = FigureCanvasTkAgg(self.testfigure(), master=self.root) #<---- !!!!!!
canvas.get_tk_widget().grid(sticky=tk.N+tk.W+tk.E+tk.S)
self.root.rowconfigure(0, weight=1)
self.root.columnconfigure(0, weight=1)
def testfigure(self):
x=np.linspace(0, 2*np.pi,100)
y=np.sin(x)
fig = mpl.figure.Figure()
sub = fig.add_subplot(111)
sub.plot(x,y)
return fig
def EXIT(self):
Top = tk.Toplevel(master=self.root)
Top.wm_iconbitmap( os.path.abspath("icon.ico")) #<---- !!!!!!
Top.transient(self.root)
Top.resizable(width=False, height=False)
Top.title("Exit")
tk.Message(Top,text="Do you really want to quit?", justify=tk.CENTER, width=300).grid(row=0,columnspan=3)
tk.Button(Top,text="YES",command=self.root.destroy).grid(row=1,column=0)
tk.Button(Top,text="No",command=self.root.destroy).grid(row=1,column=1)
tk.Button(Top,text="Maybe",command=self.root.destroy).grid(row=1,column=2)
def start(self):
self.root.mainloop()
if __name__ == '__main__':
INTERFACE().start()
I know this is an old question, but I've experienced a similar situation and have found a solution.
In my case, I've isolated the issue to the use of iconbitmap. I've managed to solve it by calling iconbitmap with the after method just before calling root.mainloop().
Example:
from tkinter import *
root = Tk()
w = Label(root, text="Hello, world!")
w.pack()
root.geometry('300x300+500+500')
root.after(50, root.iconbitmap('icon.ico'))
root.mainloop()
This method has worked on Toplevel() windows with icons as well.
Tested on Win 8.1 with Python 3.5.0.
Edit: Upon further inspection I've noticed that the behavior changes relative to root.geometry's presence as well. My initial example didn't have it and I only noticed after a few tries that it still had the same issue. The time delay in the after method doesn't seem to change anything.
Moving root.geometry below the after method yields the same issue for some reason.
Most likely, somewhere in your initialization code you're calling update or update_idletasks, which causes the current state of the GUI to be drawn on the screen.
Another possible source of the problem is if you're creating multiple instances of Tk rather than Toplevel.
Without seeing your code, though, all we can do is guess.
Your best route to solving this problem is to create a small example that has the same behavior. Not because we need it to help you, but because the effort you put into recreating the bug will likely teach you what is causing the bug.
This should work but it requires win32gui
import win32gui
def FlashMyWindow(title):
ID = win32gui.FindWindow(None, title)
win32gui.FlashWindow(ID,True)

Categories

Resources