python tkinter canvas feature, trying to use StringVar-s to draw arcs - python

im trying to create an arc with tkinter canvas widget, but whatever I do, I cant get the create_arc function to work. I tried assigning values to normal python variables in the main function body, but that doesnt work either. Here is my full code.
from tkinter import *
from tkinter import ttk
root = Tk()
emasektor = StringVar()
def arvutapalgad(*args):
try:
sissetulek.set(x+y+z)
emasektor.set(float((x/(x+y+z))*360))
isasektor = 90
lastesektor = (z/(x+y+z))*360
except ValueError:
**raam.create_arc(20, 20, 180, 180,start = 0,extent=emasektor.get(),fill='red')**

Here is a minimal example that works. Build up from this until a bit at a time until it does not work. That should tell you what is causing the problem.
import tkinter as tk
root = tk.Tk()
can = tk.Canvas(root)
can.pack()
arc = can.create_arc(100,100,200,300, fill='red')
root.mainloop()
Or start with your code and cut or comment out until it does not 'work'. Also, when posting a question, be more specific than 'does not work'. If there is a traceback, post it.

Related

Python, Tkinter - some general questions about the code

I have some general questions regarding working code below:
tkinter is library for graphic interface as I understand I can use it interchangeably with for example Kivy?
Would it be better to learn Kivy instead or other?
Lines import tkinter as tk and from tkinter import * do exactly the same, in the first one I have alias though?
In the code below, why do I have to use ttk in ttk.Progressbar?
I imported whole library with import tkinter as tk so why do i have to reimport ttk just for progress bar? (otherwise it is not working). I would expect to work sth. like tk.Progressbar
In the line btnProg = tk.Button(self.root, text = 'update', command=self.fnUpdateProgress), why method "fnUpdateProgress" can't have any variables? Whenever I add any, the button stop working? -> for example btnProg = tk.Button(self.root, text = 'update', command=self.fnUpdateProgress(24)) (ofc then some changes in def of the method itself)
I created progress bar (pb) as attribute of the class Test, but wolud it be better to define it as regular variable (without self)? To be honest, code works exactly the same.
Code:
import tkinter as tk
from tkinter import *
from tkinter import ttk
from CreateProgramMain import main
import GlobalVariables
class Test():
####################################################################################
def __init__(self):
self.Progress=0
self.root = tk.Tk()
self.root.title(GlobalVariables.strAppName)
self.root.geometry('400x200')
lbl = Label(self.root, text="Please choose environment.",font=("Arial Bold", 12))
lbl.grid(column=2, row=0,sticky='e')
def btnTestClicked():
main("TEST",self)
btnTest=tk.Button(self.root, text="Test Environment", command=btnTestClicked)
btnTest.grid(column=2, row=15)
#Place progress bar
pb = ttk.Progressbar(self.root,orient='horizontal',mode='determinate',length=200)
pb.grid(column=1, row=65, columnspan=2, padx=10, pady=20)
pb["value"]=self.Progress
pb["maximum"]=100
btnProg = tk.Button(self.root, text = 'update', command=self.fnUpdateProgress)
btnProg.grid(column=2, row=75)
self.root.mainloop()
def fnUpdateProgress(self): #why i cant insert variable inside?
pb["value"]=self.Progress
self.Progress=self.Progress+5
pb.update()
app = Test()
Thank you
it is upto you. However, tkinter and kivy both have their own syntaxes, commands, and their own usages. It might be a little difficult to convert tkinter code to kivy.
it is upto you
Yes. In the first, you have imported tkinter as tk. In the second one. You have done a wild card import. You have imported everything
Tkinter is a folder containing various modules. It contains a file called ttk.py which you have to import to access ttk.
All other classes like Label, Entry, Tk is present in __init__.py
you have to use lambda for it. If you call the function, it will be executed wlright away and the returned value is kept as the command.
Doing command=self.fnUpdateProgress(24)) will execute the function right away. Then, the returned value is kept as a command. Here, it returns None. So the command is nothing or the button is useless.
Use a lambda expression command=lambda: self.fnUpdateProgress(24))
if you don't add self it will be local to the function only. To access ot outside, it would have to be declared global, which is the point to avoid while using classes

I need a little help wth using tkinter and pillow(Python)

I am new to coding so problem might be very simple but I just dont get it.
So I am trying to upload a gif image to tkinter label. Here is my code:
from PIL import *
import PIL.Image
import tkinter as tk
from tkinter import *
root = Tk()
img = PIL.Image.open ("10.gif")
tkimage = PhotoImage(img)
label = Label(root, image=tkimage)
label.pack()
root.mainloop()
And here is the error that I am getting:
__str__ returned non-string (type GifImageFile)
I dont seem to find answer from google for this particular problem(I have tried)

Adding Tix Widget to Tkinter Container

I'm working with Tkinter in Python 2.7 on Windows 7, and found the need to create a popup box with a tree-style list of checkboxes. I could not find this in Tkinter, or ttk. I did, however, find it in Tix in the CheckList widget. I got a working standalone example using Tix, but I cannot figure out how to add my Tix.CheckList to my ttk.Frame that controls my main program.
Surely I am not forced to use Tix framework from the ground up?
import Tix
import pandas as pd
import Tkinter as tk
class TreeCheckList(object):
def __init__(self, root):
self.root = root
self.cl = Tix.CheckList(self.root)
self.cl.pack(fill=Tix.BOTH, expand=Tix.YES)
self.cl.hlist.config(bg='white', bd=0, selectmode='none', selectbackground='white', selectforeground='black', drawbranch=True, pady=5)
self.cl.hlist.add('ALL', text='All Messages')
self.cl.hlist.add('ALL.First', text='First')
self.cl.setstatus('ALL.First', "off")
self.cl.hlist.add('ALL.Second', text='Second')
self.cl.setstatus('ALL.Second', "off")
self.cl.autosetmode()
def main():
root = Tix.Tk()
top = Tix.Toplevel(root)
checklist = TreeCheckList(top)
root.update()
top.tkraise()
root.mainloop()
if __name__ == '__main__':
main()
The above code works in a standalone program using all Tix widgets. However, when I try to implement this into my larger program, I receive a TclError: invalid command name "tixCheckList"
To simulate this in the standalone, I changed the lines:
root = Tix.Tk()
top = Tix.Toplevel(root)
to
root = tk.Tk()
top = tk.Toplevel(root)
I was hoping I could just implement a Tix.Toplevel, placing it on a tk.Tk() root, but same issue.
Am I only allowed to use Tix frames when using a Tix widget, or am I misunderstanding something? If anyone has good Tix documentation, I would LOVE whatever I can get. It seems good docs on it are few and far between. Or is this same functionality included in ttk and I've just overlooked it? It seems to be one of the only things left out.
I have just learned that apparently only root needs to be a Tix class. Since Tk, and therefore ttk, classes appear to be added to the Tix root just fine (since most of them extend the Tkinter classes anyway), this appears to be a "fix". So my problem may have been solved by changing just
root = tk.Tk()
to
root = Tix.Tk()
This did require that I pull Tix into a part of my program I wasn't wanting for encapsulation purposes, but I guess there's no other way.

How to set focus in tkinter entry box

have spent a while looking for an answer. I'm new to Python but not to coding in general. Finding the various versions quite challenging!
Anyway I'm very Gui orientated and have managed to get tkinter working with Python 3.5.1
Just playing with basics and have the following code but cannot set focus to the first entry box. Have tried mEntry1.focus() and mEntry1.focus_set() but always get object has no attribute error. Any help?
from tkinter import *
def calc(*args):
try:
value1 = float(V1.get())
value2 = float(V2.get())
result.set(value1 * value2)
except ValueError:
pass
mGui = Tk()
mGui.geometry('450x450+200+200')
mGui.title('Test Gui')
V1 = StringVar()
V2 = StringVar()
result = StringVar()
mEntry1 = Entry(textvariable=V1,width=10).grid(row=0,column=0,sticky=W)
mEntry2 = Entry(textvariable=V2).grid(row=1,column=0)
mButton = Button(text='Calculate',command=calc).grid(row=3,column=0)
mlabel = Label(textvariable=result).grid(row=4,column=2)
Every Tkinter widget has the focus_set method.
The problem with your code is that the .grid method returns None. Thus
mEntry1 = Entry(textvariable=V1,width=10).grid(row=0,column=0,sticky=W)
sets mEntry1 to None, not the widget. So you need to create the widget and put it in the grid in two steps:
mEntry1 = Entry(textvariable=V1,width=10)
mEntry1.grid(row=0,column=0,sticky=W)
Of course, if you don't actually need a reference to the widget object then it's ok to do it in one step. So something like
Entry(textvariable=V1,width=10).grid(row=0,column=0,sticky=W)
would be fine.
BTW, it's not a good idea to use from tkinter import *. It imports over 130 names into your namespace, which can lead to name collisions with your own names, or with those of other modules if you also import them with a "star" import statement. It also makes the code harder to read. Instead, you can do
import tkinter as tk
and then refer to Tkinter names using the tk. prefix, eg tk.Entry instead of Entry.

Python Tkinter module not showing output

I am trying to learn Python and trying something GUI in Python and came across this Tkinter module. My code runs but the window does not appear when I run. My code is as follows:
from Tkinter import *
#to create a root window
root = Tk()
The program runs, gives no errors but the window does not show up.
Add this to your code root.mainloop(), Here's a tutorial.
In response to your comment
#Also note that `from <module> import *` is generally frowned upon
#since it can lead to namespace collisions. It's much better to only
#explicitly import the things you need.
from Tkinter import Tk, Label
root = Tk()
w = Label(root, text="Hello, world!")
w.pack()
root.mainloop()
As other answers have pointed out, you need to call mainloop on the root object.
I recommend an OO-style of programming, and I also recommend not doing a global import (ie: not 'from Tkinter import *').
Here's a template I usually start out with:
import Tkinter as tk
class ExampleView(tk.Frame):
def __init__(self, root):
tk.Frame.__init__(self, root)
l = tk.Label(self, text="your widgets go here...", anchor="c")
l.pack(side="top", fill="both", expand=True)
if __name__=='__main__':
root = tk.Tk()
view = ExampleView(root)
view.pack(side="top", fill="both", expand=True)
root.mainloop()
This makes it easy to keep your main logic at the start of the file, and keep the creation of the root and the calling of mainloop together, which I think makes the code a little bit easier to understand. It also makes reusing this code a little easier (ie: you could create a larger program where this is one of several windows that can be created)
Add root.mainloop() at the end.

Categories

Resources