I made two different projects. One using tkinter to make GUI and the other one I was learning to use customtkinter. In this project I'm trying to combine the dollar, euro and bitcoin quote code with what I learned doing GUI using customtkinter. I don't exactly know how to get this to run right now. I've read the customtkinter documentation but I couldn't find the answer. If you can help me I will be grateful haha
import customtkinter
import requests
customtkinter.set_appearance_mode("dark")
customtkinter.set_default_color_theme("dark-blue")
root = customtkinter.CTk()
root.geometry("500x350")
root.title("Cotacao Krettina")
def pegar_cotacoes():
requisicao = requests.get('https://economia.awesomeapi.com.br/json/last/USD-BRL,EUR-BRL,BTC-BRL')
requisicao_dic = requisicao.json()
cotacao_dolar = requisicao_dic ['USDBRL']['bid']
cotacao_euro = requisicao_dic ['EURBRL']['bid']
cotacao_bitcoin = requisicao_dic ['BTCBRL']['bid']
texto = f'''
Dolar: {cotacao_dolar}
Euro: {cotacao_euro}
Bitcoin: {cotacao_bitcoin}'''
texto_cotacoes["text"] = texto
frame = customtkinter.CTkFrame(master=root)
frame.pack(pady=20, padx=60, fill="both", expand=True)
button = customtkinter.CTkButton(master=frame, text="Cotar!", command=pegar_cotacoes)
button.pack(pady=12, padx=10)
texto_cotacoes = customtkinter.CTkLabel(master=root, width=120, height=25, corner_radius=8)
texto_cotacoes.pack(pady=12, padx=10)
root.mainloop()\
Related
I made some functions which grab information from websites like weather or news using Python and BeautifulSoup. Basically web scraping.
Now I would like to run them in a different window with Tkinter. How could I implement the weather function, as an example, in my code in order to have it shown not just in the terminal of my text editor but in this Tkinter window?
That's my code for the Tkinter window:
from tkinter import *
from PIL import ImageTk, Image
from weather import weather_def # that's the function I made in a different file
# main
window = Tk()
window.title('My Overview')
window.configure(background='white')
# create a entry text box
textentry = Entry(window, width=15, bg='white')
textentry.place(x=80, y=40)
# create label
label = Label(window, text='Empty label', bg='white', fg='black', font='none 12 bold')
label.place(x=80, y=120)
# add a submit button, command=click, width=10
btn = Button(window, text='Show information', command=weather_def)
btn.place(x=80, y=80)
# run the main loop
window.mainloop()
And that's the function which grabs information about the weather from a website:
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
url_weather = 'https://www.mein-wetter.com/wetter/ebermannstadt.htm'
# opening up connection, grabbing the page
uClient_weather = uReq(url_weather)
page_html_weather = uClient_weather.read()
uClient_weather.close()
# html parsing
page_soup_weather = soup(page_html_weather, "html.parser")
# grabs containers
containers_weather = page_soup_weather.find('ul', {'class': 'uldet'}).findAll('li')
# grabs time, temperature, text
def weather_def():
print('Wetter')
print('::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::')
for container in containers_weather:
time = container.findAll('h4')[0].text
temperature = container.findAll('dd', {'class': 'temp'})[0].text
image_alt = container.find('img').get('alt')
# only show weather from 6:00 to 23:00
if int(time) == 00:
break
elif int(time[1]) >= 6 or int(time[0]) > 0:
print(time + ':00 Uhr')
print(temperature)
print(image_alt)
print('-----------------------------------------')
Hi #jumuell and welcome to Stack Overflow. I have seen the comments, but I am answering your question because I found a problem that the others did not.
For your problem, you need to show multiple lines of text as a result. The Text widget allows multiple lines to be typed in it. But the logic part and the GUI part are in separate files.
Create a new Text widget in the GUI file.
name_of_text_widget = Text(window)
name_of_text_widget.pack
(You can change pack to grid or place as per your wish.)
Then in the function, make a list which has all the data to be returned. In your case it would be:
#Add this line at the bottom of the function named `weather_def`
return ['Wetter', ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::', time + ':00 Uhr',
temperature, image_alt, '-----------------------------------------']
Create a new function and link it in the GUI file to a button(instead of directly calling weather_def function).Then type the following code in there:
def function_name():
#This function should be in the GUI file
list_from_weather_output = weather_def()
for i in list_from_weather_output:
name_of_text_widget.insert(END, i)
In the picture: I designed an interface with tkinter by pulling data over mongodb. I want it to appear as a mongodb-fed list.
How can I do it.
very uneven like that.
Also, I don't want _id to appear.
the code I wrote:
import pymongo
import tkinter as tk
from tkinter import messagebox
client = pymongo.MongoClient("secure")
koleksiyon = client["dukkan"]
db = koleksiyon["yaglar"]
master = tk.Tk()
master.geometry("300x300")
def buttonCallback():
uruns = tk.Toplevel()
uruns .geometry("300x300")
mas = tk.Label(uruns, text="Urunler listesi")
veriler = db.find().sort("db")
for x in veriler:
urunn = tk.Label(uruns, text=x)
urunn.pack()
mas.pack()
urunler = tk.Button(master, text="Tüm Ürünler", command=buttonCallback)
label_1 = tk.Label(master, text="Bolat Aktar ürün yönetim sistemi")
label_1.grid(row=0, column=0)
urunler.grid(row=1, column=0)
master.mainloop()
How can I list regularly?
Search for Python Dictionaries and f-Strings, and you can edit your code like that:
urunn = tk.Label(uruns, text=f"Marka: {x['urunmarkasi']}, "
f"Adı: {x['urunadi']}, "
f"Boyut: {x['boyut']}, "
f"Fiyat: {x['fiyat']}")
I tried creating a program that will take in the symptoms of a person and return the disease they have. This is the GUI part of the project.
from tkinter import *
root = Tk()
root.title("Health GUI")
root.geometry("1000x625")
symptoms_list = []
def print_symptoms():
print(symptoms_list)
def typeSymptoms():
gap3 = Label(text="").pack()
symptoms_entry = Text(width=50, height=20)
symptoms_entry.pack()
symptoms_list.append(symptoms_entry.get(1.0, END))
done_symptoms = Button(text="I have written my symptoms", width=25, height=5, command=lol)
done_symptoms.pack()
gap1 = Label(text="").pack()
title = Label(text="HEALTH GUI", font=30).pack()
gap2 = Label(text="").pack()
start_button = Button(text="Click here to start", width=30, height=5, command=typeSymptoms, font=20).pack()
root.mainloop()
Just for simplicity, I tried printing out the symptoms given by the user to the console but it gives me a list with '\n'. Please help. Thanks!(PS: I lerned Tkinter day before yesterday so I don't know much)
At the moment, your variable symptoms_list just holds the contents of the newly created Text widget, since you append this content at startup.
If you want to add the symptoms to the list, you need to have your function lol() that you call when pressing the button.
This function should look something like:
def lol():
symptoms_text = symptoms_entry.get(1.0, END)
symptoms_list = symptoms_text.split('\n')
print_symptoms()
However, your widgets and the symptoms_list would have to be global variables in order for this program to work. It would probably be better, while you are getting acquainted with Tkinter, to learn how to create a dialog as Class with attributes. That makes sharing values between methods so much easier.
This is a project using Python 3.6.2 and tkinter 36
So, the chunk of code posted below is a slightly trimmed version of a UI that I started making. After a bit of bodging and discovering the config method, I had my theme toggle function working.
The code below essentially toggles the background color of the Label and Text widgets with the config method.
This works, however, the buttons turn invisible until I mouseover them.
I've attempted using update and update_idletasks to no avail (there is the possibility that I haven't been using them correctly, as there was no example posted on usage in my sources.)
How do I update widgets when the parents change?
Is that would be difficult, would there be a less difficult workaround?
from tkinter import *
root = Tk()
root.minsize(width=600, height=400)
DarkTheme = ['#102030',
'#203040',
'#101010',
'#f0f0f0',
]
LightTheme = ['#c0d0e0',
'#d0e0f0',
'#f0f0f0',
'#101010'
]
Theme = DarkTheme
SBar = Label(root, width=22, fg=Theme[3], bg=Theme[0])
SBar.pack_propagate(0)
SBar.pack(side=LEFT, fill=Y)
Text = Text(root, fg=Theme[3], bg=Theme[2])
Text.pack_propagate(0)
Text.pack(side=RIGHT, fill=BOTH, expand=1)
def ThemeSet():
global SBar
global Text
SBar.config(fg=Theme[3], bg=Theme[0])
Text.config(fg=Theme[3], bg=Theme[2])
def SwapTheme():
global Theme
if Theme == DarkTheme:
Theme = LightTheme
ThemeSet()
elif Theme == LightTheme:
Theme = DarkTheme
ThemeSet()
themetoggle = Button(SBar, text = 'Theme Toggle', command = SwapTheme)
themetoggle.pack()
def AddLetter():
global Text
Text.insert(END, "hello, ")
Text.insert(END, "world")
addletter = Button(SBar, text = 'Add letter', command = AddLetter)
addletter.pack()
root.mainloop()
I am fairly new to python and am currently working on a school project, my aim is to create a search bar that can be used to search a data file, however I am struggling to get the search bar to work correctly. I am using the tkinter entry widget.
When I call .get(), the string in the entry widget is not printed. Here is my code...
from tkinter import *
def searchButton():
text = searched.get()
print (text)
def drawStatWindow():
global searched
statWindow = Tk()
statWindow.title("View Statistics")
statWindow.config(bg = "grey")
statWindow.geometry('800x900')
searched = StringVar()
searchBox = Entry(statWindow, textvariable = searched)
searchBox.place(x= 450, y=50, width = 200, height = 24)
enterButton = tkinter.Button(statWindow, text ="Enter", command =searchButton)
enterButton.config(height = 1, width = 4)
enterButton.place(x=652, y=50)
drawStatWindow()
When I type a string into the entry widget and press the enter button, nothing happens.
Like I say I am not very experienced and this is my first project, but after reading about the tkinter entry widgets I can't understand why this won't work.
I am using python V3.4.0
Thanks.
Your code lacks a call to mainloop(). You could try adding it to the end of the drawStatWindow() function:
statWindow.mainloop()
You might want to restructure your code into a class. This allows you to avoid using global variables and generally provides better organisation for your application:
from tkinter import *
class App:
def __init__(self, statWindow):
statWindow.title("View Statistics")
statWindow.config(bg = "grey")
statWindow.geometry('800x900')
self.searched = StringVar()
searchBox = Entry(statWindow, textvariable=self.searched)
searchBox.place(x= 450, y=50, width = 200, height = 24)
enterButton = Button(statWindow, text ="Enter", command=self.searchButton)
enterButton.config(height = 1, width = 4)
enterButton.place(x=652, y=50)
def searchButton(self):
text = self.searched.get()
print(text)
root = Tk()
app = App(root)
root.mainloop()
You have to add mainloop() because tkinter needs it to run.
If you run code in IDLE which use tkinter then IDLE runs own mainloop() and code can work but normally you have to add mainloop() at the end.
And you have to remove tkinter in tkinter.Button.
from tkinter import *
def searchButton():
text = searched.get()
print(text)
def drawStatWindow():
global searched
statWindow = Tk()
statWindow.title("View Statistics")
statWindow.config(bg="grey")
statWindow.geometry('800x900')
searched = StringVar()
searchBox = Entry(statWindow, textvariable=searched)
searchBox.place(x= 450, y=50, width=200, height=24)
# remove `tkinter` in `tkinter.Button`
enterButton = Button(statWindow, text="Enter", command=searchButton)
enterButton.config(height=1, width=4)
enterButton.place(x=652, y=50)
# add `mainloop()`
statWindow.mainloop()
drawStatWindow()
No need to use textvariable, you should use this:
searchBox = Entry(statWindow)
searchBox.focus_set()
searchBox.place(x= 450, y=50, width = 200, height = 24)
then you will be able to use searchBox.get(), that will be a string.