我用 kivy python 创建了一个日历,带有一个微调下拉小部件,可以计算当天的工作小时数。我遇到的问题是我无法将字体设置为 30。我尝试过在网上找到的无知的示例和描述,但都不起作用。 这是罪人:
def show_osark_dialog(self): # 为 OSARK 创建一个弹出窗口 osark_popup = 弹出窗口(title='Matematik', size_hint=(无, 无), size=(700, 400), auto_dismiss=True)
# Content layout for the popup
osark_content = GridLayout(cols=1, padding=10, spacing=10)
# Create spinners for selecting times
time_spinner1 = Spinner(text='00:00', values=[f'{h:02d}:{m:02d}' for h in range(24) for m in range(0, 60, 15)])
time_spinner2 = Spinner(text='00:00', values=[f'{h:02d}:{m:02d}' for h in range(24) for m in range(0, 60, 15)])
# Function to calculate time difference
def calculate_time_difference(instance, value):
time1 = datetime.strptime(time_spinner1.text, '%H:%M')
time2 = datetime.strptime(time_spinner2.text, '%H:%M')
time_diff = abs(time2 - time1)
osark_label.text = f'Jobbade timmar: {time_diff}'
# Bind the calculate_time_difference function to spinner values change
time_spinner1.bind(text=calculate_time_difference)
time_spinner2.bind(text=calculate_time_difference)
# Label to display the time difference
osark_label = Label(text='Välj start och sluttid ...')
# Add spinners and label to the content layout
osark_content.add_widget(time_spinner1)
osark_content.add_widget(time_spinner2)
osark_content.add_widget(osark_label)
# Set the content of the popup window
osark_popup.content = osark_content
# Open the popup window
osark_popup.open()
如何在此下拉小部件中获取字体 30?
Spinner
类默认使用 SpinnerOption
类来表示选项。但是,您可以使用 option_cls
属性指定您自己的选项类。
例如,这是一个选项类别的可能性:
class MySpinnerOption(Button):
def __init__(self, **kwargs):
super(MySpinnerOption, self).__init__(**kwargs)
self.font_size = 30
self.size_hint_y = None
self.height = 30
然后您可以在创建
Spinner
时指定新的选项类:
time_spinner1 = Spinner(text='00:00', values=[f'{h:02d}:{m:02d}' for h in range(24) for m in range(0, 60, 15)], option_cls='MySpinnerOption')
如果您希望
Spinner
的底部具有相同的字体大小,只需将font_size=30
添加到Spinner
即可。请参阅文档。
谢谢您的回答。 我查看了您的代码并尝试实现它,但只是出现错误。我是一个初学者,刚刚开始使用这个代码库,所以我很难调试我不理解的代码。但是如果你看看我上面的代码,在这种情况下你会如何实现你的代码?.
如果您看到我的整个代码,可能会更容易:
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.core.window import Window
from kivy.uix.popup import Popup
from kivy.uix.textinput import TextInput
from kivy.uix.dropdown import DropDown
from kivy.uix.label import Label
from kivy.uix.spinner import Spinner
from kivy.clock import Clock
import calendar
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from datetime import datetime, timedelta
import webbrowser
# ___________________________________________________________________________________________
SPREADSHEET_ID = '----------'
API_KEY = '---------'
# Define credentials JSON data
credentials_json = {
"type": "service_account",
"project_id": "timmraport",
"private_key_id": "-------",
"private_key": "-----",
"client_id": "--------",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/timraport%40timmraport.iam.gserviceaccount.com"
}
# Authorize using credentials
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_dict(credentials_json, scope)
client = gspread.authorize(credentials)
# Access the spreadsheet ------------------------------------------------------------
spreadsheet = client.open_by_key(SPREADSHEET_ID)
class CalendarApp(App):
def build(self):
self.year = 2024 # Initial year
self.month = 1 # Initial month
self.cal = calendar.monthcalendar(self.year, self.month)
self.today = datetime.now().day # Get today's day
layout = GridLayout(cols=7, padding=1, spacing=1)
self.update_calendar(layout)
return layout
def update_calendar(self, layout):
layout.clear_widgets()
days = ['Mo', 'Ti', 'On', 'To', 'Fr', 'Lö', 'Sö']
# Add day labels
for day in days:
label = Button(text=day, background_color='#1c99e0', font_size=60)
layout.add_widget(label)
# Add day buttons
for week in self.cal:
for day in week:
if day == 0:
layout.add_widget(Button(text='', background_color=(0.09, 0.1, 0.15, 0)))
else:
btn = Button(text=str(day), background_color='#171a27', font_size=50)
if self.is_date(day):
btn.border = (1, 1, 1, 1)
btn.border_width = (0.5, 0.5)
if day == self.today: # Highlight today's date
btn.background_color='#c86fff' # Change to the specified color
btn.bind(on_press=lambda instance, day=day: self.show_popup(day))
layout.add_widget(btn)
def is_date(self, day):
# Check if a given day is within the month's days
if day in range(1, calendar.monthrange(self.year, self.month)[1] + 1):
return True
return False
def show_popup(self, day):
self.popup = Popup(title='Datumet du valt att ändra är: ' + str(day),
size_hint=(None, None), size=(700, 450),
auto_dismiss=False)
content = GridLayout(cols=1, padding=10, spacing=10)
# Text input for number
self.number_input = TextInput(hint_text='Skriv in dina timmar ...', font_size=50)
content.add_widget(self.number_input)
# Dropdown list
dropdown = DropDown()
for option in ['Normal arbetstid', 'Övertidstimmar', 'Storhelgstillägg']:
btn = Button(text=option, size_hint_y=None, height=110, background_color='#ffffff', font_size=30)
btn.bind(on_release=lambda btn: dropdown.select(btn.text))
dropdown.add_widget(btn)
main_button = Button(text='Arbetstider', size_hint=(None, None), size=(310, 80), background_color='#a2a3ac', font_size=30)
main_button.bind(on_release=dropdown.open)
dropdown.bind(on_select=lambda instance, x: setattr(main_button, 'text', x))
# Create a nested GridLayout for buttons
buttons_layout = GridLayout(cols=2, spacing=10)
# Add the main button and the link button
buttons_layout.add_widget(main_button)
# Add open popup"
link_button = Button(text='Ändra inlagda tider', size_hint=(None, None), size=(310, 80), background_color='#a2a3ac', font_size=25)
link_button.bind(on_release=lambda instance: self.show_text_popup())
buttons_layout.add_widget(link_button)
content.add_widget(buttons_layout)
# Buttons layout
buttons_layout = GridLayout(cols=2, spacing=1)
# OK button
ok_button = Button(text='OK', background_color='#171a27', font_size=40)
ok_button.bind(on_press=lambda instance: self.add_to_google_sheets(day, main_button.text))
buttons_layout.add_widget(ok_button)
# Cancel button
cancel_button = Button(text='Avbryt', background_color='#171a27', font_size=40)
cancel_button.bind(on_press=self.cancel_popup)
buttons_layout.add_widget(cancel_button)
content.add_widget(buttons_layout)
# Button to open OSARK dialog
osark_button = Button(text='--- Matematik ---', background_color='#171a27', font_size=20)
osark_button.bind(on_press=lambda instance: self.show_osark_dialog())
content.add_widget(osark_button)
self.popup.content = content
self.popup.open()
def show_text_popup(self):
# Create a popup window for text information
text_popup = Popup(title='Information', size_hint=(None, None), size=(700, 450), auto_dismiss=True)
# Create a GridLayout for the content of the popup
text_content = GridLayout(cols=1, padding=10, spacing=10)
# Text input for information
text_input = TextInput(text="Önskar du att ändra i dina inlagda arbetstider, kan du bara skriva in din nya tid, och din gamla tid skrivs då över. Önskar du att radera tiden helt, kan du NOLLA UT din inskrivna tid med en '0' nolla. Då raderas tiden het från kalendern för den dagen.",
font_size=25, halign='left', readonly=True, multiline=True, size_hint_y=800)
text_input.bind(minimum_height=text_input.setter('height'))
text_content.add_widget(text_input)
# Create a GridLayout for buttons
buttons_layout = GridLayout(cols=3, spacing=10, size_hint_y=None, height=80)
# Create a button to clear the calendar data
clear_button = Button(text="Rensa kalendern", background_color='#171a27', font_size=25)
clear_button.bind(on_release=self.clear_calendar_data)
buttons_layout.add_widget(clear_button)
# Add "BI BI" button next to "Rensa allt i min kalender" button
bi_bi_button = Button(text="Timmarraport", background_color='#171a27', font_size=25)
bi_bi_button.bind(on_release=lambda instance: webbrowser.open("https://docs.google.com/spreadsheets/d/1xQV_e_kmp9-ECTVX-9pAP4u4F1ug0JFD58vCRWgc5vE/export?format=pdf"))
buttons_layout.add_widget(bi_bi_button)
# Add KUCOS button
kucos_button = Button(text="Min lön", background_color='#171a27', font_size=25)
kucos_button.bind(on_release=lambda instance: self.show_kucos_popup())
buttons_layout.add_widget(kucos_button)
# Add buttons layout to the content layout
text_content.add_widget(buttons_layout)
# Set the content of the popup window
text_popup.content = text_content
# Open the popup window
text_popup.open()
def show_osark_dialog(self):
# Create a popup window for OSARK
osark_popup = Popup(title='Matematik', size_hint=(None, None), size=(700, 400), auto_dismiss=True)
# Content layout for the popup
osark_content = GridLayout(cols=1, padding=10, spacing=10)
# Create spinners for selecting times
time_spinner1 = Spinner(text='00:00', values=[f'{h:02d}:{m:02d}' for h in range(24) for m in range(0, 60, 15)])
time_spinner2 = Spinner(text='00:00', values=[f'{h:02d}:{m:02d}' for h in range(24) for m in range(0, 60, 15)])
# Function to calculate time difference
def calculate_time_difference(instance, value):
time1 = datetime.strptime(time_spinner1.text, '%H:%M')
time2 = datetime.strptime(time_spinner2.text, '%H:%M')
time_diff = abs(time2 - time1)
osark_label.text = f'Jobbade timmar: {time_diff}'
# Bind the calculate_time_difference function to spinner values change
time_spinner1.bind(text=calculate_time_difference)
time_spinner2.bind(text=calculate_time_difference)
# Label to display the time difference
osark_label = Label(text='Välj start och sluttid ...')
# Add spinners and label to the content layout
osark_content.add_widget(time_spinner1)
osark_content.add_widget(time_spinner2)
osark_content.add_widget(osark_label)
# Set the content of the popup window
osark_popup.content = osark_content
# Open the popup window
osark_popup.open()
def show_kucos_popup(self):
try:
# Retrieve data from Google Sheets
worksheet = spreadsheet.get_worksheet(0)
data_h41 = worksheet.acell('H41').value
data_h43 = worksheet.acell('H43').value
data_i43 = worksheet.acell('I43').value
# Create a popup window for KUCOS information
kucos_popup = Popup(title='Information', size_hint=(None, None), size=(700, 350), auto_dismiss=True)
# Create a GridLayout for the content of the popup
kucos_content = GridLayout(cols=3, padding=10, spacing=10, )
# Add text to the GridLayout
kucos_content.add_widget(Label(text="Mina timmar", color=[49/255, 227/255, 191/255, 1], font_size=35))
kucos_content.add_widget(Label(text="Innan skatt", color=[49/255, 227/255, 191/255, 1], font_size=35))
kucos_content.add_widget(Label(text="Min lön ut", color=[49/255, 227/255, 191/255, 1], font_size=35))
# Add retrieved data to the GridLayout
kucos_content.add_widget(Label(text=data_h41, font_size=40))
kucos_content.add_widget(Label(text=data_h43, font_size=30))
kucos_content.add_widget(Label(text=data_i43, font_size=30))
# Set the content of the popup window
kucos_popup.content = kucos_content
# Open the popup window
kucos_popup.open()
except Exception as e:
print("Error fetching data:", e)
def cancel_popup(self, instance):
self.popup.dismiss()
def add_to_google_sheets(self, day, column):
try:
number = self.number_input.text.replace(',', '.') # Replace comma with dot for decimal values
number = float(number) # Convert to float
# Check if a choice has been made in the dropdown menu
if column == 'Arbetstider':
# Show error message if no choice has been made
self.number_input.text = 'Välj typ av arbetstider !!! ...'
return
# Calculate the row number based on the day selected
row = 8 + day
# Determine the column index based on the selected option
if column == 'Normal arbetstid':
column_index = 4 # Column D
elif column == 'Övertidstimmar':
column_index = 5 # Column E
elif column == 'Storhelgstillägg':
column_index = 6 # Column F
# Select the first worksheet
worksheet = spreadsheet.get_worksheet(0)
# Update the cell with the calculated row and column index
worksheet.update_cell(row, column_index, number)
# Close the popup window
self.popup.dismiss()
# Refresh the calendar layout
self.update_calendar(self.root)
except Exception as e:
print("Error adding data to Google Sheets:", e)
def clear_calendar_data(self, instance):
try:
# Select the first worksheet
worksheet = spreadsheet.get_worksheet(0)
# Clear all data in the worksheet
worksheet.clear()
# Close the popup window
instance.parent.parent.parent.dismiss()
# Refresh the calendar layout
self.update_calendar(self.root)
except Exception as e:
print("Error clearing calendar data:", e)
if __name__ == '__main__':
CalendarApp().run()